xref: /freebsd/contrib/llvm-project/llvm/lib/Support/Unix/Path.inc (revision 1342eb5a832fa10e689a29faab3acb6054e4778c)
1//===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Unix specific implementation of the Path API.
10//
11//===----------------------------------------------------------------------===//
12
13//===----------------------------------------------------------------------===//
14//=== WARNING: Implementation here must contain only generic UNIX code that
15//===          is guaranteed to work on *all* UNIX variants.
16//===----------------------------------------------------------------------===//
17
18#include "Unix.h"
19#include <limits.h>
20#include <stdio.h>
21#include <sys/stat.h>
22#include <fcntl.h>
23#ifdef HAVE_UNISTD_H
24#include <unistd.h>
25#endif
26#ifdef HAVE_SYS_MMAN_H
27#include <sys/mman.h>
28#endif
29
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#endif
40#elif defined(__FreeBSD__)
41#include <osreldate.h>
42#if __FreeBSD_version >= 1300057
43#include <sys/auxv.h>
44#else
45#include <machine/elf.h>
46extern char **environ;
47#endif
48#elif defined(__DragonFly__)
49#include <sys/mount.h>
50#elif defined(__MVS__)
51#include "llvm/Support/AutoConvert.h"
52#include <sys/ps.h>
53#endif
54
55// Both stdio.h and cstdio are included via different paths and
56// stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
57// either.
58#undef ferror
59#undef feof
60
61#if !defined(PATH_MAX)
62// For GNU Hurd
63#if defined(__GNU__)
64#define PATH_MAX 4096
65#elif defined(__MVS__)
66#define PATH_MAX _XOPEN_PATH_MAX
67#endif
68#endif
69
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 statvfs
76#define FSTATVFS fstatvfs
77#define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
78#else
79#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#else
86#if defined(HAVE_LINUX_NFS_FS_H)
87#include <linux/nfs_fs.h>
88#endif
89#if defined(HAVE_LINUX_SMB_H)
90#include <linux/smb.h>
91#endif
92#endif
93#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> to
98// `uint_t`; however, <sys/types.h> does not always declare `uint`. We provide
99// the typedef prior to including <sys/vmount.h> to work around this issue.
100typedef uint_t uint;
101#include <sys/vmount.h>
102#else
103#include <sys/mount.h>
104#endif
105#define STATVFS statfs
106#define FSTATVFS fstatfs
107#define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
108#endif
109
110#if defined(__NetBSD__) || defined(__DragonFly__) || defined(__GNU__) ||       \
111    defined(__MVS__)
112#define STATVFS_F_FLAG(vfs) (vfs).f_flag
113#else
114#define STATVFS_F_FLAG(vfs) (vfs).f_flags
115#endif
116
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 terminated
137  // 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 the
190/// 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 it
194  // from there is much faster than calling dladdr, especially for large
195  // 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 is
205  // preferred, if available.  /proc/curproc/file and the KERN_PROC_PATHNAME
206  // sysctl may not return the desired path if there are multiple hardlinks
207  // to the file.
208  char exe_path[PATH_MAX];
209#if __FreeBSD_version >= 1300057
210  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#else
216  // elf_aux_info(AT_EXECPATH, ... is not available in all supported versions,
217  // fall back to finding the ELF auxiliary vectors after the process's
218  // 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#endif
231  // 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 null
242      // 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 null
262    // 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, on
267    // GNU/Hurd, /proc/self/exe is a symlink to the path that was used to start
268    // the program, and not the eventual binary file. Therefore, call realpath
269    // 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#else
277    char real_path[PATH_MAX];
278    if (realpath(exe_path, real_path))
279      return std::string(real_path);
280#endif
281  }
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] only
288  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 of
332  // the actual executable.
333  char link_path[PATH_MAX];
334  if (realpath(DLInfo.dli_fname, link_path))
335    return link_path;
336#else
337#error GetMainExecutable is not implemented on this host yet.
338#endif
339  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 by
425// 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 should
464  // only be involved in the creation and deletion of regular files.  This
465  // check ensures that what we're trying to erase is a regular file. It
466  // effectively prevents LLVM from erasing things like /dev/null, any block
467  // 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_MAGIC
482#define NFS_SUPER_MAGIC 0x6969
483#endif
484#ifndef SMB_SUPER_MAGIC
485#define SMB_SUPER_MAGIC 0x517B
486#endif
487#ifndef CIFS_MAGIC_NUMBER
488#define CIFS_MAGIC_NUMBER 0xFF534D42
489#endif
490#if defined(__GNU__) && ((__GLIBC__ < 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ < 39)))
491  switch ((uint32_t)Vfs.__f_type) {
492#else
493  switch ((uint32_t)Vfs.f_type) {
494#endif
495  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 mounted
516  // target
517  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 concurrent
522  // 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 the
556  // conservative answer.
557  return false;
558#else
559  return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
560#endif
561}
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 on
596  // OS X with HFS+ it does.
597  if (::ftruncate(FD, Size) == -1)
598    return errnoAsErrorCode();
599
600  return std::error_code();
601}
602
603static int convertAccessMode(AccessMode Mode) {
604  switch (Mode) {
605  case AccessMode::Exist:
606    return F_OK;
607  case AccessMode::Write:
608    return W_OK;
609  case AccessMode::Execute:
610    return R_OK | X_OK; // scripts also need R_OK.
611  }
612  llvm_unreachable("invalid enum");
613}
614
615std::error_code access(const Twine &Path, AccessMode Mode) {
616  SmallString<128> PathStorage;
617  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
618
619  if (::access(P.begin(), convertAccessMode(Mode)) == -1)
620    return errnoAsErrorCode();
621
622  if (Mode == AccessMode::Execute) {
623    // Don't say that directories are executable.
624    struct stat buf;
625    if (0 != stat(P.begin(), &buf))
626      return errc::permission_denied;
627    if (!S_ISREG(buf.st_mode))
628      return errc::permission_denied;
629  }
630
631  return std::error_code();
632}
633
634bool can_execute(const Twine &Path) {
635  return !access(Path, AccessMode::Execute);
636}
637
638bool equivalent(file_status A, file_status B) {
639  assert(status_known(A) && status_known(B));
640  return A.fs_st_dev == B.fs_st_dev && A.fs_st_ino == B.fs_st_ino;
641}
642
643std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
644  file_status fsA, fsB;
645  if (std::error_code ec = status(A, fsA))
646    return ec;
647  if (std::error_code ec = status(B, fsB))
648    return ec;
649  result = equivalent(fsA, fsB);
650  return std::error_code();
651}
652
653static void expandTildeExpr(SmallVectorImpl<char> &Path) {
654  StringRef PathStr(Path.begin(), Path.size());
655  if (PathStr.empty() || !PathStr.starts_with("~"))
656    return;
657
658  PathStr = PathStr.drop_front();
659  StringRef Expr =
660      PathStr.take_until([](char c) { return path::is_separator(c); });
661  StringRef Remainder = PathStr.substr(Expr.size() + 1);
662  SmallString<128> Storage;
663  if (Expr.empty()) {
664    // This is just ~/..., resolve it to the current user's home dir.
665    if (!path::home_directory(Storage)) {
666      // For some reason we couldn't get the home directory.  Just exit.
667      return;
668    }
669
670    // Overwrite the first character and insert the rest.
671    Path[0] = Storage[0];
672    Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
673    return;
674  }
675
676  // This is a string of the form ~username/, look up this user's entry in the
677  // password database.
678  std::unique_ptr<char[]> Buf;
679  long BufSize = sysconf(_SC_GETPW_R_SIZE_MAX);
680  if (BufSize <= 0)
681    BufSize = 16384;
682  Buf = std::make_unique<char[]>(BufSize);
683  struct passwd Pwd;
684  std::string User = Expr.str();
685  struct passwd *Entry = nullptr;
686  getpwnam_r(User.c_str(), &Pwd, Buf.get(), BufSize, &Entry);
687
688  if (!Entry || !Entry->pw_dir) {
689    // Unable to look up the entry, just return back the original path.
690    return;
691  }
692
693  Storage = Remainder;
694  Path.clear();
695  Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
696  llvm::sys::path::append(Path, Storage);
697}
698
699void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
700  dest.clear();
701  if (path.isTriviallyEmpty())
702    return;
703
704  path.toVector(dest);
705  expandTildeExpr(dest);
706}
707
708static file_type typeForMode(mode_t Mode) {
709  if (S_ISDIR(Mode))
710    return file_type::directory_file;
711  else if (S_ISREG(Mode))
712    return file_type::regular_file;
713  else if (S_ISBLK(Mode))
714    return file_type::block_file;
715  else if (S_ISCHR(Mode))
716    return file_type::character_file;
717  else if (S_ISFIFO(Mode))
718    return file_type::fifo_file;
719  else if (S_ISSOCK(Mode))
720    return file_type::socket_file;
721  else if (S_ISLNK(Mode))
722    return file_type::symlink_file;
723  return file_type::type_unknown;
724}
725
726static std::error_code fillStatus(int StatRet, const struct stat &Status,
727                                  file_status &Result) {
728  if (StatRet != 0) {
729    std::error_code EC = errnoAsErrorCode();
730    if (EC == errc::no_such_file_or_directory)
731      Result = file_status(file_type::file_not_found);
732    else
733      Result = file_status(file_type::status_error);
734    return EC;
735  }
736
737  uint32_t atime_nsec, mtime_nsec;
738#if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
739  atime_nsec = Status.st_atimespec.tv_nsec;
740  mtime_nsec = Status.st_mtimespec.tv_nsec;
741#elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
742  atime_nsec = Status.st_atim.tv_nsec;
743  mtime_nsec = Status.st_mtim.tv_nsec;
744#else
745  atime_nsec = mtime_nsec = 0;
746#endif
747
748  perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
749  Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev,
750                       Status.st_nlink, Status.st_ino, Status.st_atime,
751                       atime_nsec, Status.st_mtime, mtime_nsec, Status.st_uid,
752                       Status.st_gid, Status.st_size);
753
754  return std::error_code();
755}
756
757std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
758  SmallString<128> PathStorage;
759  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
760
761  struct stat Status;
762  int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
763  return fillStatus(StatRet, Status, Result);
764}
765
766std::error_code status(int FD, file_status &Result) {
767  struct stat Status;
768  int StatRet = ::fstat(FD, &Status);
769  return fillStatus(StatRet, Status, Result);
770}
771
772unsigned getUmask() {
773  // Chose arbitary new mask and reset the umask to the old mask.
774  // umask(2) never fails so ignore the return of the second call.
775  unsigned Mask = ::umask(0);
776  (void)::umask(Mask);
777  return Mask;
778}
779
780std::error_code setPermissions(const Twine &Path, perms Permissions) {
781  SmallString<128> PathStorage;
782  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
783
784  if (::chmod(P.begin(), Permissions))
785    return errnoAsErrorCode();
786  return std::error_code();
787}
788
789std::error_code setPermissions(int FD, perms Permissions) {
790  if (::fchmod(FD, Permissions))
791    return errnoAsErrorCode();
792  return std::error_code();
793}
794
795std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
796                                                 TimePoint<> ModificationTime) {
797#if defined(HAVE_FUTIMENS)
798  timespec Times[2];
799  Times[0] = sys::toTimeSpec(AccessTime);
800  Times[1] = sys::toTimeSpec(ModificationTime);
801  if (::futimens(FD, Times))
802    return errnoAsErrorCode();
803  return std::error_code();
804#elif defined(HAVE_FUTIMES)
805  timeval Times[2];
806  Times[0] = sys::toTimeVal(
807      std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
808  Times[1] =
809      sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
810          ModificationTime));
811  if (::futimes(FD, Times))
812    return errnoAsErrorCode();
813  return std::error_code();
814#elif defined(__MVS__)
815  attrib_t Attr;
816  memset(&Attr, 0, sizeof(Attr));
817  Attr.att_atimechg = 1;
818  Attr.att_atime = sys::toTimeT(AccessTime);
819  Attr.att_mtimechg = 1;
820  Attr.att_mtime = sys::toTimeT(ModificationTime);
821  if (::__fchattr(FD, &Attr, sizeof(Attr)) != 0)
822    return errnoAsErrorCode();
823  return std::error_code();
824#else
825#warning Missing futimes() and futimens()
826  return make_error_code(errc::function_not_supported);
827#endif
828}
829
830std::error_code mapped_file_region::init(int FD, uint64_t Offset,
831                                         mapmode Mode) {
832  assert(Size != 0);
833
834  int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
835  int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
836#if defined(MAP_NORESERVE)
837  flags |= MAP_NORESERVE;
838#endif
839#if defined(__APPLE__)
840  //----------------------------------------------------------------------
841  // Newer versions of MacOSX have a flag that will allow us to read from
842  // binaries whose code signature is invalid without crashing by using
843  // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
844  // is mapped we can avoid crashing and return zeroes to any pages we try
845  // to read if the media becomes unavailable by using the
846  // MAP_RESILIENT_MEDIA flag.  These flags are only usable when mapping
847  // with PROT_READ, so take care not to specify them otherwise.
848  //----------------------------------------------------------------------
849  if (Mode == readonly) {
850#if defined(MAP_RESILIENT_CODESIGN)
851    flags |= MAP_RESILIENT_CODESIGN;
852#endif
853#if defined(MAP_RESILIENT_MEDIA)
854    flags |= MAP_RESILIENT_MEDIA;
855#endif
856  }
857#endif // #if defined (__APPLE__)
858
859  Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
860  if (Mapping == MAP_FAILED)
861    return errnoAsErrorCode();
862  return std::error_code();
863}
864
865mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
866                                       uint64_t offset, std::error_code &ec)
867    : Size(length), Mode(mode) {
868  (void)Mode;
869  ec = init(fd, offset, mode);
870  if (ec)
871    copyFrom(mapped_file_region());
872}
873
874void mapped_file_region::unmapImpl() {
875  if (Mapping)
876    ::munmap(Mapping, Size);
877}
878
879void mapped_file_region::dontNeedImpl() {
880  assert(Mode == mapped_file_region::readonly);
881  if (!Mapping)
882    return;
883#if defined(__MVS__) || defined(_AIX)
884    // If we don't have madvise, or it isn't beneficial, treat this as a no-op.
885#elif defined(POSIX_MADV_DONTNEED)
886  ::posix_madvise(Mapping, Size, POSIX_MADV_DONTNEED);
887#else
888  ::madvise(Mapping, Size, MADV_DONTNEED);
889#endif
890}
891
892int mapped_file_region::alignment() { return Process::getPageSizeEstimate(); }
893
894std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
895                                                     StringRef path,
896                                                     bool follow_symlinks) {
897  SmallString<128> path_null(path);
898  DIR *directory = ::opendir(path_null.c_str());
899  if (!directory)
900    return errnoAsErrorCode();
901
902  it.IterationHandle = reinterpret_cast<intptr_t>(directory);
903  // Add something for replace_filename to replace.
904  path::append(path_null, ".");
905  it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
906  return directory_iterator_increment(it);
907}
908
909std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
910  if (it.IterationHandle)
911    ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
912  it.IterationHandle = 0;
913  it.CurrentEntry = directory_entry();
914  return std::error_code();
915}
916
917static file_type direntType(dirent *Entry) {
918  // Most platforms provide the file type in the dirent: Linux/BSD/Mac.
919  // The DTTOIF macro lets us reuse our status -> type conversion.
920  // Note that while glibc provides a macro to see if this is supported,
921  // _DIRENT_HAVE_D_TYPE, it's not defined on BSD/Mac, so we test for the
922  // d_type-to-mode_t conversion macro instead.
923#if defined(DTTOIF)
924  return typeForMode(DTTOIF(Entry->d_type));
925#else
926  // Other platforms such as Solaris require a stat() to get the type.
927  return file_type::type_unknown;
928#endif
929}
930
931std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
932  errno = 0;
933  dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));
934  if (CurDir == nullptr && errno != 0) {
935    return errnoAsErrorCode();
936  } else if (CurDir != nullptr) {
937    StringRef Name(CurDir->d_name);
938    if ((Name.size() == 1 && Name[0] == '.') ||
939        (Name.size() == 2 && Name[0] == '.' && Name[1] == '.'))
940      return directory_iterator_increment(It);
941    It.CurrentEntry.replace_filename(Name, direntType(CurDir));
942  } else {
943    return directory_iterator_destruct(It);
944  }
945
946  return std::error_code();
947}
948
949ErrorOr<basic_file_status> directory_entry::status() const {
950  file_status s;
951  if (auto EC = fs::status(Path, s, FollowSymlinks))
952    return EC;
953  return s;
954}
955
956//
957// FreeBSD optionally provides /proc/self/fd, but it is incompatible with
958// Linux. The thing to use is realpath.
959//
960#if !defined(__FreeBSD__) && !defined(__OpenBSD__)
961#define TRY_PROC_SELF_FD
962#endif
963
964#if !defined(F_GETPATH) && defined(TRY_PROC_SELF_FD)
965static bool hasProcSelfFD() {
966  // If we have a /proc filesystem mounted, we can quickly establish the
967  // real name of the file with readlink
968  static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
969  return Result;
970}
971#endif
972
973static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
974                           FileAccess Access) {
975  int Result = 0;
976  if (Access == FA_Read)
977    Result |= O_RDONLY;
978  else if (Access == FA_Write)
979    Result |= O_WRONLY;
980  else if (Access == (FA_Read | FA_Write))
981    Result |= O_RDWR;
982
983  // This is for compatibility with old code that assumed OF_Append implied
984  // would open an existing file.  See Windows/Path.inc for a longer comment.
985  if (Flags & OF_Append)
986    Disp = CD_OpenAlways;
987
988  if (Disp == CD_CreateNew) {
989    Result |= O_CREAT; // Create if it doesn't exist.
990    Result |= O_EXCL;  // Fail if it does.
991  } else if (Disp == CD_CreateAlways) {
992    Result |= O_CREAT; // Create if it doesn't exist.
993    Result |= O_TRUNC; // Truncate if it does.
994  } else if (Disp == CD_OpenAlways) {
995    Result |= O_CREAT; // Create if it doesn't exist.
996  } else if (Disp == CD_OpenExisting) {
997    // Nothing special, just don't add O_CREAT and we get these semantics.
998  }
999
1000// Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
1001// calling write(). Instead we need to use lseek() to set offset to EOF after
1002// open().
1003#ifndef __MVS__
1004  if (Flags & OF_Append)
1005    Result |= O_APPEND;
1006#endif
1007
1008#ifdef O_CLOEXEC
1009  if (!(Flags & OF_ChildInherit))
1010    Result |= O_CLOEXEC;
1011#endif
1012
1013  return Result;
1014}
1015
1016std::error_code openFile(const Twine &Name, int &ResultFD,
1017                         CreationDisposition Disp, FileAccess Access,
1018                         OpenFlags Flags, unsigned Mode) {
1019  int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
1020
1021  SmallString<128> Storage;
1022  StringRef P = Name.toNullTerminatedStringRef(Storage);
1023  // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
1024  // when open is overloaded, such as in Bionic.
1025  auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
1026  if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
1027    return errnoAsErrorCode();
1028#ifndef O_CLOEXEC
1029  if (!(Flags & OF_ChildInherit)) {
1030    int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
1031    (void)r;
1032    assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
1033  }
1034#endif
1035
1036#ifdef __MVS__
1037  /* Reason about auto-conversion and file tags. Setting the file tag only
1038   * applies if file is opened in write mode:
1039   *
1040   * Text file:
1041   *                  File exists       File created
1042   * CD_CreateNew     n/a               conv: on
1043   *                                    tag: set 1047
1044   * CD_CreateAlways  conv: auto        conv: on
1045   *                  tag: auto 1047    tag: set 1047
1046   * CD_OpenAlways    conv: auto        conv: on
1047   *                  tag: auto 1047    tag: set 1047
1048   * CD_OpenExisting  conv: auto        n/a
1049   *                  tag: unchanged
1050   *
1051   * Binary file:
1052   *                  File exists       File created
1053   * CD_CreateNew     n/a               conv: off
1054   *                                    tag: set binary
1055   * CD_CreateAlways  conv: off         conv: off
1056   *                  tag: auto binary  tag: set binary
1057   * CD_OpenAlways    conv: off         conv: off
1058   *                  tag: auto binary  tag: set binary
1059   * CD_OpenExisting  conv: off         n/a
1060   *                  tag: unchanged
1061   *
1062   * Actions:
1063   *   conv: off        -> auto-conversion is turned off
1064   *   conv: on         -> auto-conversion is turned on
1065   *   conv: auto       -> auto-conversion is turned on if the file is untagged
1066   *   tag: set 1047    -> set the file tag to text encoded in 1047
1067   *   tag: set binary  -> set the file tag to binary
1068   *   tag: auto 1047   -> set file tag to 1047 if not set
1069   *   tag: auto binary -> set file tag to binary if not set
1070   *   tag: unchanged   -> do not care about the file tag
1071   *
1072   * It is not possible to distinguish between the cases "file exists" and
1073   * "file created". In the latter case, the file tag is not set and the file
1074   * size is zero. The decision table boils down to:
1075   *
1076   * the file tag is set if
1077   *   - the file is opened for writing
1078   *   - the create disposition is not equal to CD_OpenExisting
1079   *   - the file tag is not set
1080   *   - the file size is zero
1081   *
1082   * This only applies if the file is a regular file. E.g. enabling
1083   * auto-conversion for reading from /dev/null results in error EINVAL when
1084   * calling read().
1085   *
1086   * Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
1087   * calling write(). Instead we need to use lseek() to set offset to EOF after
1088   * open().
1089   */
1090  if ((Flags & OF_Append) && lseek(ResultFD, 0, SEEK_END) == -1)
1091    return errnoAsErrorCode();
1092  struct stat Stat;
1093  if (fstat(ResultFD, &Stat) == -1)
1094    return errnoAsErrorCode();
1095  if (S_ISREG(Stat.st_mode)) {
1096    bool DoSetTag = (Access & FA_Write) && (Disp != CD_OpenExisting) &&
1097                    !Stat.st_tag.ft_txtflag && !Stat.st_tag.ft_ccsid &&
1098                    Stat.st_size == 0;
1099    if (Flags & OF_Text) {
1100      if (auto EC = llvm::enableAutoConversion(ResultFD))
1101        return EC;
1102      if (DoSetTag) {
1103        if (auto EC = llvm::setzOSFileTag(ResultFD, CCSID_IBM_1047, true))
1104          return EC;
1105      }
1106    } else {
1107      if (auto EC = llvm::disableAutoConversion(ResultFD))
1108        return EC;
1109      if (DoSetTag) {
1110        if (auto EC = llvm::setzOSFileTag(ResultFD, FT_BINARY, false))
1111          return EC;
1112      }
1113    }
1114  }
1115#endif
1116
1117  return std::error_code();
1118}
1119
1120Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,
1121                             FileAccess Access, OpenFlags Flags,
1122                             unsigned Mode) {
1123
1124  int FD;
1125  std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
1126  if (EC)
1127    return errorCodeToError(EC);
1128  return FD;
1129}
1130
1131std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1132                                OpenFlags Flags,
1133                                SmallVectorImpl<char> *RealPath) {
1134  std::error_code EC =
1135      openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
1136  if (EC)
1137    return EC;
1138
1139  // Attempt to get the real name of the file, if the user asked
1140  if (!RealPath)
1141    return std::error_code();
1142  RealPath->clear();
1143#if defined(F_GETPATH)
1144  // When F_GETPATH is availble, it is the quickest way to get
1145  // the real path name.
1146  char Buffer[PATH_MAX];
1147  if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
1148    RealPath->append(Buffer, Buffer + strlen(Buffer));
1149#else
1150  char Buffer[PATH_MAX];
1151#if defined(TRY_PROC_SELF_FD)
1152  if (hasProcSelfFD()) {
1153    char ProcPath[64];
1154    snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
1155    ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
1156    if (CharCount > 0)
1157      RealPath->append(Buffer, Buffer + CharCount);
1158  } else {
1159#endif
1160    SmallString<128> Storage;
1161    StringRef P = Name.toNullTerminatedStringRef(Storage);
1162
1163    // Use ::realpath to get the real path name
1164    if (::realpath(P.begin(), Buffer) != nullptr)
1165      RealPath->append(Buffer, Buffer + strlen(Buffer));
1166#if defined(TRY_PROC_SELF_FD)
1167  }
1168#endif
1169#endif
1170  return std::error_code();
1171}
1172
1173Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1174                                       SmallVectorImpl<char> *RealPath) {
1175  file_t ResultFD;
1176  std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
1177  if (EC)
1178    return errorCodeToError(EC);
1179  return ResultFD;
1180}
1181
1182file_t getStdinHandle() { return 0; }
1183file_t getStdoutHandle() { return 1; }
1184file_t getStderrHandle() { return 2; }
1185
1186Expected<size_t> readNativeFile(file_t FD, MutableArrayRef<char> Buf) {
1187#if defined(__APPLE__)
1188  size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
1189#else
1190  size_t Size = Buf.size();
1191#endif
1192  ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
1193  if (ssize_t(NumRead) == -1)
1194    return errorCodeToError(errnoAsErrorCode());
1195// The underlying operation on these platforms allow opening directories
1196// for reading in more cases than other platforms.
1197#if defined(__MVS__) || defined(_AIX)
1198  struct stat Status;
1199  if (fstat(FD, &Status) == -1)
1200    return errorCodeToError(errnoAsErrorCode());
1201  if (S_ISDIR(Status.st_mode))
1202    return errorCodeToError(make_error_code(errc::is_a_directory));
1203#endif
1204  return NumRead;
1205}
1206
1207Expected<size_t> readNativeFileSlice(file_t FD, MutableArrayRef<char> Buf,
1208                                     uint64_t Offset) {
1209#if defined(__APPLE__)
1210  size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
1211#else
1212  size_t Size = Buf.size();
1213#endif
1214#ifdef HAVE_PREAD
1215  ssize_t NumRead =
1216      sys::RetryAfterSignal(-1, ::pread, FD, Buf.data(), Size, Offset);
1217#else
1218  if (lseek(FD, Offset, SEEK_SET) == -1)
1219    return errorCodeToError(errnoAsErrorCode());
1220  ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
1221#endif
1222  if (NumRead == -1)
1223    return errorCodeToError(errnoAsErrorCode());
1224  return NumRead;
1225}
1226
1227std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout) {
1228  auto Start = std::chrono::steady_clock::now();
1229  auto End = Start + Timeout;
1230  do {
1231    struct flock Lock;
1232    memset(&Lock, 0, sizeof(Lock));
1233    Lock.l_type = F_WRLCK;
1234    Lock.l_whence = SEEK_SET;
1235    Lock.l_start = 0;
1236    Lock.l_len = 0;
1237    if (::fcntl(FD, F_SETLK, &Lock) != -1)
1238      return std::error_code();
1239    int Error = errno;
1240    if (Error != EACCES && Error != EAGAIN)
1241      return std::error_code(Error, std::generic_category());
1242    usleep(1000);
1243  } while (std::chrono::steady_clock::now() < End);
1244  return make_error_code(errc::no_lock_available);
1245}
1246
1247std::error_code lockFile(int FD) {
1248  struct flock Lock;
1249  memset(&Lock, 0, sizeof(Lock));
1250  Lock.l_type = F_WRLCK;
1251  Lock.l_whence = SEEK_SET;
1252  Lock.l_start = 0;
1253  Lock.l_len = 0;
1254  if (::fcntl(FD, F_SETLKW, &Lock) != -1)
1255    return std::error_code();
1256  return errnoAsErrorCode();
1257}
1258
1259std::error_code unlockFile(int FD) {
1260  struct flock Lock;
1261  Lock.l_type = F_UNLCK;
1262  Lock.l_whence = SEEK_SET;
1263  Lock.l_start = 0;
1264  Lock.l_len = 0;
1265  if (::fcntl(FD, F_SETLK, &Lock) != -1)
1266    return std::error_code();
1267  return errnoAsErrorCode();
1268}
1269
1270std::error_code closeFile(file_t &F) {
1271  file_t TmpF = F;
1272  F = kInvalidFile;
1273  return Process::SafelyCloseFileDescriptor(TmpF);
1274}
1275
1276template <typename T>
1277static std::error_code remove_directories_impl(const T &Entry,
1278                                               bool IgnoreErrors) {
1279  std::error_code EC;
1280  directory_iterator Begin(Entry, EC, false);
1281  directory_iterator End;
1282  while (Begin != End) {
1283    auto &Item = *Begin;
1284    ErrorOr<basic_file_status> st = Item.status();
1285    if (st) {
1286      if (is_directory(*st)) {
1287        EC = remove_directories_impl(Item, IgnoreErrors);
1288        if (EC && !IgnoreErrors)
1289          return EC;
1290      }
1291
1292      EC = fs::remove(Item.path(), true);
1293      if (EC && !IgnoreErrors)
1294        return EC;
1295    } else if (!IgnoreErrors) {
1296      return st.getError();
1297    }
1298
1299    Begin.increment(EC);
1300    if (EC && !IgnoreErrors)
1301      return EC;
1302  }
1303  return std::error_code();
1304}
1305
1306std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1307  auto EC = remove_directories_impl(path, IgnoreErrors);
1308  if (EC && !IgnoreErrors)
1309    return EC;
1310  EC = fs::remove(path, true);
1311  if (EC && !IgnoreErrors)
1312    return EC;
1313  return std::error_code();
1314}
1315
1316std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1317                          bool expand_tilde) {
1318  dest.clear();
1319  if (path.isTriviallyEmpty())
1320    return std::error_code();
1321
1322  if (expand_tilde) {
1323    SmallString<128> Storage;
1324    path.toVector(Storage);
1325    expandTildeExpr(Storage);
1326    return real_path(Storage, dest, false);
1327  }
1328
1329  SmallString<128> Storage;
1330  StringRef P = path.toNullTerminatedStringRef(Storage);
1331  char Buffer[PATH_MAX];
1332  if (::realpath(P.begin(), Buffer) == nullptr)
1333    return errnoAsErrorCode();
1334  dest.append(Buffer, Buffer + strlen(Buffer));
1335  return std::error_code();
1336}
1337
1338std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group) {
1339  auto FChown = [&]() { return ::fchown(FD, Owner, Group); };
1340  // Retry if fchown call fails due to interruption.
1341  if ((sys::RetryAfterSignal(-1, FChown)) < 0)
1342    return errnoAsErrorCode();
1343  return std::error_code();
1344}
1345
1346} // end namespace fs
1347
1348namespace path {
1349
1350bool home_directory(SmallVectorImpl<char> &result) {
1351  std::unique_ptr<char[]> Buf;
1352  char *RequestedDir = getenv("HOME");
1353  if (!RequestedDir) {
1354    long BufSize = sysconf(_SC_GETPW_R_SIZE_MAX);
1355    if (BufSize <= 0)
1356      BufSize = 16384;
1357    Buf = std::make_unique<char[]>(BufSize);
1358    struct passwd Pwd;
1359    struct passwd *pw = nullptr;
1360    getpwuid_r(getuid(), &Pwd, Buf.get(), BufSize, &pw);
1361    if (pw && pw->pw_dir)
1362      RequestedDir = pw->pw_dir;
1363  }
1364  if (!RequestedDir)
1365    return false;
1366
1367  result.clear();
1368  result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1369  return true;
1370}
1371
1372static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
1373#if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
1374  // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
1375  // macros defined in <unistd.h> on darwin >= 9
1376  int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR : _CS_DARWIN_USER_CACHE_DIR;
1377  size_t ConfLen = confstr(ConfName, nullptr, 0);
1378  if (ConfLen > 0) {
1379    do {
1380      Result.resize(ConfLen);
1381      ConfLen = confstr(ConfName, Result.data(), Result.size());
1382    } while (ConfLen > 0 && ConfLen != Result.size());
1383
1384    if (ConfLen > 0) {
1385      assert(Result.back() == 0);
1386      Result.pop_back();
1387      return true;
1388    }
1389
1390    Result.clear();
1391  }
1392#endif
1393  return false;
1394}
1395
1396bool user_config_directory(SmallVectorImpl<char> &result) {
1397#ifdef __APPLE__
1398  // Mac: ~/Library/Preferences/
1399  if (home_directory(result)) {
1400    append(result, "Library", "Preferences");
1401    return true;
1402  }
1403#else
1404  // XDG_CONFIG_HOME as defined in the XDG Base Directory Specification:
1405  // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1406  if (const char *RequestedDir = getenv("XDG_CONFIG_HOME")) {
1407    result.clear();
1408    result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1409    return true;
1410  }
1411#endif
1412  // Fallback: ~/.config
1413  if (!home_directory(result)) {
1414    return false;
1415  }
1416  append(result, ".config");
1417  return true;
1418}
1419
1420bool cache_directory(SmallVectorImpl<char> &result) {
1421#ifdef __APPLE__
1422  if (getDarwinConfDir(false /*tempDir*/, result)) {
1423    return true;
1424  }
1425#else
1426  // XDG_CACHE_HOME as defined in the XDG Base Directory Specification:
1427  // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1428  if (const char *RequestedDir = getenv("XDG_CACHE_HOME")) {
1429    result.clear();
1430    result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1431    return true;
1432  }
1433#endif
1434  if (!home_directory(result)) {
1435    return false;
1436  }
1437  append(result, ".cache");
1438  return true;
1439}
1440
1441static const char *getEnvTempDir() {
1442  // Check whether the temporary directory is specified by an environment
1443  // variable.
1444  const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1445  for (const char *Env : EnvironmentVariables) {
1446    if (const char *Dir = std::getenv(Env))
1447      return Dir;
1448  }
1449
1450  return nullptr;
1451}
1452
1453static const char *getDefaultTempDir(bool ErasedOnReboot) {
1454#ifdef P_tmpdir
1455  if ((bool)P_tmpdir)
1456    return P_tmpdir;
1457#endif
1458
1459  if (ErasedOnReboot)
1460    return "/tmp";
1461  return "/var/tmp";
1462}
1463
1464void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1465  Result.clear();
1466
1467  if (ErasedOnReboot) {
1468    // There is no env variable for the cache directory.
1469    if (const char *RequestedDir = getEnvTempDir()) {
1470      Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1471      return;
1472    }
1473  }
1474
1475  if (getDarwinConfDir(ErasedOnReboot, Result))
1476    return;
1477
1478  const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1479  Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1480}
1481
1482} // end namespace path
1483
1484namespace fs {
1485
1486#ifdef __APPLE__
1487/// This implementation tries to perform an APFS CoW clone of the file,
1488/// which can be much faster and uses less space.
1489/// Unfortunately fcopyfile(3) does not support COPYFILE_CLONE, so the
1490/// file descriptor variant of this function still uses the default
1491/// implementation.
1492std::error_code copy_file(const Twine &From, const Twine &To) {
1493  std::string FromS = From.str();
1494  std::string ToS = To.str();
1495#if __has_builtin(__builtin_available)
1496  if (__builtin_available(macos 10.12, *)) {
1497    // Optimistically try to use clonefile() and handle errors, rather than
1498    // calling stat() to see if it'll work.
1499    //
1500    // Note: It's okay if From is a symlink. In contrast to the behaviour of
1501    // copyfile() with COPYFILE_CLONE, clonefile() clones targets (not the
1502    // symlink itself) unless the flag CLONE_NOFOLLOW is passed.
1503    if (!clonefile(FromS.c_str(), ToS.c_str(), 0))
1504      return std::error_code();
1505
1506    auto Errno = errno;
1507    switch (Errno) {
1508    case EEXIST:  // To already exists.
1509    case ENOTSUP: // Device does not support cloning.
1510    case EXDEV:   // From and To are on different devices.
1511      break;
1512    default:
1513      // Anything else will also break copyfile().
1514      return std::error_code(Errno, std::generic_category());
1515    }
1516
1517    // TODO: For EEXIST, profile calling fs::generateUniqueName() and
1518    // clonefile() in a retry loop (then rename() on success) before falling
1519    // back to copyfile(). Depending on the size of the file this could be
1520    // cheaper.
1521  }
1522#endif
1523  if (!copyfile(FromS.c_str(), ToS.c_str(), /*State=*/NULL, COPYFILE_DATA))
1524    return std::error_code();
1525  return errnoAsErrorCode();
1526}
1527#endif // __APPLE__
1528
1529} // end namespace fs
1530
1531} // end namespace sys
1532} // end namespace llvm
1533