xref: /freebsd/contrib/llvm-project/llvm/lib/Support/Unix/Path.inc (revision 4d3fc8b0570b29fb0d6ee9525f104d52176ff0d4)
1//===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Unix specific implementation of the Path API.
10//
11//===----------------------------------------------------------------------===//
12
13//===----------------------------------------------------------------------===//
14//=== WARNING: Implementation here must contain only generic UNIX code that
15//===          is guaranteed to work on *all* UNIX variants.
16//===----------------------------------------------------------------------===//
17
18#include "Unix.h"
19#include <limits.h>
20#include <stdio.h>
21#if HAVE_SYS_STAT_H
22#include <sys/stat.h>
23#endif
24#if HAVE_FCNTL_H
25#include <fcntl.h>
26#endif
27#ifdef HAVE_UNISTD_H
28#include <unistd.h>
29#endif
30#ifdef HAVE_SYS_MMAN_H
31#include <sys/mman.h>
32#endif
33
34#include <dirent.h>
35#include <pwd.h>
36#include <sys/file.h>
37
38#ifdef __APPLE__
39#include <mach-o/dyld.h>
40#include <sys/attr.h>
41#include <copyfile.h>
42#if __has_include(<sys/clonefile.h>)
43#include <sys/clonefile.h>
44#endif
45#elif defined(__FreeBSD__)
46#include <osreldate.h>
47#if __FreeBSD_version >= 1300057
48#include <sys/auxv.h>
49#else
50#include <machine/elf.h>
51extern char **environ;
52#endif
53#elif defined(__DragonFly__)
54#include <sys/mount.h>
55#elif defined(__MVS__)
56#include "llvm/Support/AutoConvert.h"
57#include <sys/ps.h>
58#endif
59
60// Both stdio.h and cstdio are included via different paths and
61// stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
62// either.
63#undef ferror
64#undef feof
65
66#if !defined(PATH_MAX)
67// For GNU Hurd
68#if defined(__GNU__)
69#define PATH_MAX 4096
70#elif defined(__MVS__)
71#define PATH_MAX _XOPEN_PATH_MAX
72#endif
73#endif
74
75#include <sys/types.h>
76#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) &&   \
77    !defined(__linux__) && !defined(__FreeBSD_kernel__) && !defined(_AIX)
78#include <sys/statvfs.h>
79#define STATVFS statvfs
80#define FSTATVFS fstatvfs
81#define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
82#else
83#if defined(__OpenBSD__) || defined(__FreeBSD__)
84#include <sys/mount.h>
85#include <sys/param.h>
86#elif defined(__linux__)
87#if defined(HAVE_LINUX_MAGIC_H)
88#include <linux/magic.h>
89#else
90#if defined(HAVE_LINUX_NFS_FS_H)
91#include <linux/nfs_fs.h>
92#endif
93#if defined(HAVE_LINUX_SMB_H)
94#include <linux/smb.h>
95#endif
96#endif
97#include <sys/vfs.h>
98#elif defined(_AIX)
99#include <sys/statfs.h>
100
101// <sys/vmount.h> depends on `uint` to be a typedef from <sys/types.h> to
102// `uint_t`; however, <sys/types.h> does not always declare `uint`. We provide
103// the typedef prior to including <sys/vmount.h> to work around this issue.
104typedef uint_t uint;
105#include <sys/vmount.h>
106#else
107#include <sys/mount.h>
108#endif
109#define STATVFS statfs
110#define FSTATVFS fstatfs
111#define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
112#endif
113
114#if defined(__NetBSD__) || defined(__DragonFly__) || defined(__GNU__) || \
115    defined(__MVS__)
116#define STATVFS_F_FLAG(vfs) (vfs).f_flag
117#else
118#define STATVFS_F_FLAG(vfs) (vfs).f_flags
119#endif
120
121using namespace llvm;
122
123namespace llvm {
124namespace sys  {
125namespace fs {
126
127const file_t kInvalidFile = -1;
128
129#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) ||     \
130    defined(__minix) || defined(__FreeBSD_kernel__) || defined(__linux__) ||   \
131    defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX) || defined(__GNU__) || \
132    (defined(__sun__) && defined(__svr4__))
133static int
134test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
135{
136  struct stat sb;
137  char fullpath[PATH_MAX];
138
139  int chars = snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
140  // We cannot write PATH_MAX characters because the string will be terminated
141  // with a null character. Fail if truncation happened.
142  if (chars >= PATH_MAX)
143    return 1;
144  if (!realpath(fullpath, ret))
145    return 1;
146  if (stat(fullpath, &sb) != 0)
147    return 1;
148
149  return 0;
150}
151
152static char *
153getprogpath(char ret[PATH_MAX], const char *bin)
154{
155  if (bin == nullptr)
156    return nullptr;
157
158  /* First approach: absolute path. */
159  if (bin[0] == '/') {
160    if (test_dir(ret, "/", bin) == 0)
161      return ret;
162    return nullptr;
163  }
164
165  /* Second approach: relative path. */
166  if (strchr(bin, '/')) {
167    char cwd[PATH_MAX];
168    if (!getcwd(cwd, PATH_MAX))
169      return nullptr;
170    if (test_dir(ret, cwd, bin) == 0)
171      return ret;
172    return nullptr;
173  }
174
175  /* Third approach: $PATH */
176  char *pv;
177  if ((pv = getenv("PATH")) == nullptr)
178    return nullptr;
179  char *s = strdup(pv);
180  if (!s)
181    return nullptr;
182  char *state;
183  for (char *t = strtok_r(s, ":", &state); t != nullptr;
184       t = strtok_r(nullptr, ":", &state)) {
185    if (test_dir(ret, t, bin) == 0) {
186      free(s);
187      return ret;
188    }
189  }
190  free(s);
191  return nullptr;
192}
193#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
194
195/// GetMainExecutable - Return the path to the main executable, given the
196/// value of argv[0] from program startup.
197std::string getMainExecutableImpl(const char *argv0, void *MainAddr) {
198#if defined(__APPLE__)
199  // On OS X the executable path is saved to the stack by dyld. Reading it
200  // from there is much faster than calling dladdr, especially for large
201  // binaries with symbols.
202  char exe_path[PATH_MAX];
203  uint32_t size = sizeof(exe_path);
204  if (_NSGetExecutablePath(exe_path, &size) == 0) {
205    char link_path[PATH_MAX];
206    if (realpath(exe_path, link_path))
207      return link_path;
208  }
209#elif defined(__FreeBSD__)
210  // On FreeBSD if the exec path specified in ELF auxiliary vectors is
211  // preferred, if available.  /proc/curproc/file and the KERN_PROC_PATHNAME
212  // sysctl may not return the desired path if there are multiple hardlinks
213  // to the file.
214  char exe_path[PATH_MAX];
215#if __FreeBSD_version >= 1300057
216  if (elf_aux_info(AT_EXECPATH, exe_path, sizeof(exe_path)) == 0) {
217    char link_path[PATH_MAX];
218    if (realpath(exe_path, link_path))
219      return link_path;
220  }
221#else
222  // elf_aux_info(AT_EXECPATH, ... is not available in all supported versions,
223  // fall back to finding the ELF auxiliary vectors after the process's
224  // environment.
225  char **p = ::environ;
226  while (*p++ != 0)
227    ;
228  // Iterate through auxiliary vectors for AT_EXECPATH.
229  for (Elf_Auxinfo *aux = (Elf_Auxinfo *)p; aux->a_type != AT_NULL; aux++) {
230    if (aux->a_type == AT_EXECPATH) {
231      char link_path[PATH_MAX];
232      if (realpath((char *)aux->a_un.a_ptr, link_path))
233        return link_path;
234    }
235  }
236#endif
237  // Fall back to argv[0] if auxiliary vectors are not available.
238  if (getprogpath(exe_path, argv0) != NULL)
239    return exe_path;
240#elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(__minix) ||       \
241    defined(__DragonFly__) || defined(__FreeBSD_kernel__) || defined(_AIX)
242  const char *curproc = "/proc/curproc/file";
243  char exe_path[PATH_MAX];
244  if (sys::fs::exists(curproc)) {
245    ssize_t len = readlink(curproc, exe_path, sizeof(exe_path));
246    if (len > 0) {
247      // Null terminate the string for realpath. readlink never null
248      // terminates its output.
249      len = std::min(len, ssize_t(sizeof(exe_path) - 1));
250      exe_path[len] = '\0';
251      return exe_path;
252    }
253  }
254  // If we don't have procfs mounted, fall back to argv[0]
255  if (getprogpath(exe_path, argv0) != NULL)
256    return exe_path;
257#elif defined(__linux__) || defined(__CYGWIN__) || defined(__gnu_hurd__)
258  char exe_path[PATH_MAX];
259  const char *aPath = "/proc/self/exe";
260  if (sys::fs::exists(aPath)) {
261    // /proc is not always mounted under Linux (chroot for example).
262    ssize_t len = readlink(aPath, exe_path, sizeof(exe_path));
263    if (len < 0)
264      return "";
265
266    // Null terminate the string for realpath. readlink never null
267    // terminates its output.
268    len = std::min(len, ssize_t(sizeof(exe_path) - 1));
269    exe_path[len] = '\0';
270
271    // On Linux, /proc/self/exe always looks through symlinks. However, on
272    // GNU/Hurd, /proc/self/exe is a symlink to the path that was used to start
273    // the program, and not the eventual binary file. Therefore, call realpath
274    // so this behaves the same on all platforms.
275#if _POSIX_VERSION >= 200112 || defined(__GLIBC__)
276    if (char *real_path = realpath(exe_path, nullptr)) {
277      std::string ret = std::string(real_path);
278      free(real_path);
279      return ret;
280    }
281#else
282    char real_path[PATH_MAX];
283    if (realpath(exe_path, real_path))
284      return std::string(real_path);
285#endif
286  }
287  // Fall back to the classical detection.
288  if (getprogpath(exe_path, argv0))
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_DLFCN_H) && defined(HAVE_DLADDR)
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 {
355  return fs_st_nlinks;
356}
357
358ErrorOr<space_info> disk_space(const Twine &Path) {
359  struct STATVFS Vfs;
360  if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
361    return std::error_code(errno, std::generic_category());
362  auto FrSize = STATVFS_F_FRSIZE(Vfs);
363  space_info SpaceInfo;
364  SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
365  SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
366  SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
367  return SpaceInfo;
368}
369
370std::error_code current_path(SmallVectorImpl<char> &result) {
371  result.clear();
372
373  const char *pwd = ::getenv("PWD");
374  llvm::sys::fs::file_status PWDStatus, DotStatus;
375  if (pwd && llvm::sys::path::is_absolute(pwd) &&
376      !llvm::sys::fs::status(pwd, PWDStatus) &&
377      !llvm::sys::fs::status(".", DotStatus) &&
378      PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
379    result.append(pwd, pwd + strlen(pwd));
380    return std::error_code();
381  }
382
383  result.resize_for_overwrite(PATH_MAX);
384
385  while (true) {
386    if (::getcwd(result.data(), result.size()) == nullptr) {
387      // See if there was a real error.
388      if (errno != ENOMEM) {
389        result.clear();
390        return std::error_code(errno, std::generic_category());
391      }
392      // Otherwise there just wasn't enough space.
393      result.resize_for_overwrite(result.capacity() * 2);
394    } else
395      break;
396  }
397
398  result.truncate(strlen(result.data()));
399  return std::error_code();
400}
401
402std::error_code set_current_path(const Twine &path) {
403  SmallString<128> path_storage;
404  StringRef p = path.toNullTerminatedStringRef(path_storage);
405
406  if (::chdir(p.begin()) == -1)
407    return std::error_code(errno, std::generic_category());
408
409  return std::error_code();
410}
411
412std::error_code create_directory(const Twine &path, bool IgnoreExisting,
413                                 perms Perms) {
414  SmallString<128> path_storage;
415  StringRef p = path.toNullTerminatedStringRef(path_storage);
416
417  if (::mkdir(p.begin(), Perms) == -1) {
418    if (errno != EEXIST || !IgnoreExisting)
419      return std::error_code(errno, std::generic_category());
420  }
421
422  return std::error_code();
423}
424
425// Note that we are using symbolic link because hard links are not supported by
426// all filesystems (SMB doesn't).
427std::error_code create_link(const Twine &to, const Twine &from) {
428  // Get arguments.
429  SmallString<128> from_storage;
430  SmallString<128> to_storage;
431  StringRef f = from.toNullTerminatedStringRef(from_storage);
432  StringRef t = to.toNullTerminatedStringRef(to_storage);
433
434  if (::symlink(t.begin(), f.begin()) == -1)
435    return std::error_code(errno, std::generic_category());
436
437  return std::error_code();
438}
439
440std::error_code create_hard_link(const Twine &to, const Twine &from) {
441  // Get arguments.
442  SmallString<128> from_storage;
443  SmallString<128> to_storage;
444  StringRef f = from.toNullTerminatedStringRef(from_storage);
445  StringRef t = to.toNullTerminatedStringRef(to_storage);
446
447  if (::link(t.begin(), f.begin()) == -1)
448    return std::error_code(errno, std::generic_category());
449
450  return std::error_code();
451}
452
453std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
454  SmallString<128> path_storage;
455  StringRef p = path.toNullTerminatedStringRef(path_storage);
456
457  struct stat buf;
458  if (lstat(p.begin(), &buf) != 0) {
459    if (errno != ENOENT || !IgnoreNonExisting)
460      return std::error_code(errno, std::generic_category());
461    return std::error_code();
462  }
463
464  // Note: this check catches strange situations. In all cases, LLVM should
465  // only be involved in the creation and deletion of regular files.  This
466  // check ensures that what we're trying to erase is a regular file. It
467  // effectively prevents LLVM from erasing things like /dev/null, any block
468  // special file, or other things that aren't "regular" files.
469  if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
470    return make_error_code(errc::operation_not_permitted);
471
472  if (::remove(p.begin()) == -1) {
473    if (errno != ENOENT || !IgnoreNonExisting)
474      return std::error_code(errno, std::generic_category());
475  }
476
477  return std::error_code();
478}
479
480static bool is_local_impl(struct STATVFS &Vfs) {
481#if defined(__linux__) || defined(__GNU__)
482#ifndef NFS_SUPER_MAGIC
483#define NFS_SUPER_MAGIC 0x6969
484#endif
485#ifndef SMB_SUPER_MAGIC
486#define SMB_SUPER_MAGIC 0x517B
487#endif
488#ifndef CIFS_MAGIC_NUMBER
489#define CIFS_MAGIC_NUMBER 0xFF534D42
490#endif
491#ifdef __GNU__
492  switch ((uint32_t)Vfs.__f_type) {
493#else
494  switch ((uint32_t)Vfs.f_type) {
495#endif
496  case NFS_SUPER_MAGIC:
497  case SMB_SUPER_MAGIC:
498  case CIFS_MAGIC_NUMBER:
499    return false;
500  default:
501    return true;
502  }
503#elif defined(__CYGWIN__)
504  // Cygwin doesn't expose this information; would need to use Win32 API.
505  return false;
506#elif defined(__Fuchsia__)
507  // Fuchsia doesn't yet support remote filesystem mounts.
508  return true;
509#elif defined(__EMSCRIPTEN__)
510  // Emscripten doesn't currently support remote filesystem mounts.
511  return true;
512#elif defined(__HAIKU__)
513  // Haiku doesn't expose this information.
514  return false;
515#elif defined(__sun)
516  // statvfs::f_basetype contains a null-terminated FSType name of the mounted target
517  StringRef fstype(Vfs.f_basetype);
518  // NFS is the only non-local fstype??
519  return !fstype.equals("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 std::error_code(errno, std::generic_category());
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 std::error_code(errno, std::generic_category());
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 std::error_code(errno, std::generic_category());
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 std::error_code(errno, std::generic_category());
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 std::error_code(errno, std::generic_category());
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 &&
641         A.fs_st_ino == B.fs_st_ino;
642}
643
644std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
645  file_status fsA, fsB;
646  if (std::error_code ec = status(A, fsA))
647    return ec;
648  if (std::error_code ec = status(B, fsB))
649    return ec;
650  result = equivalent(fsA, fsB);
651  return std::error_code();
652}
653
654static void expandTildeExpr(SmallVectorImpl<char> &Path) {
655  StringRef PathStr(Path.begin(), Path.size());
656  if (PathStr.empty() || !PathStr.startswith("~"))
657    return;
658
659  PathStr = PathStr.drop_front();
660  StringRef Expr =
661      PathStr.take_until([](char c) { return path::is_separator(c); });
662  StringRef Remainder = PathStr.substr(Expr.size() + 1);
663  SmallString<128> Storage;
664  if (Expr.empty()) {
665    // This is just ~/..., resolve it to the current user's home dir.
666    if (!path::home_directory(Storage)) {
667      // For some reason we couldn't get the home directory.  Just exit.
668      return;
669    }
670
671    // Overwrite the first character and insert the rest.
672    Path[0] = Storage[0];
673    Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
674    return;
675  }
676
677  // This is a string of the form ~username/, look up this user's entry in the
678  // password database.
679  struct passwd *Entry = nullptr;
680  std::string User = Expr.str();
681  Entry = ::getpwnam(User.c_str());
682
683  if (!Entry) {
684    // Unable to look up the entry, just return back the original path.
685    return;
686  }
687
688  Storage = Remainder;
689  Path.clear();
690  Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
691  llvm::sys::path::append(Path, Storage);
692}
693
694
695void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
696  dest.clear();
697  if (path.isTriviallyEmpty())
698    return;
699
700  path.toVector(dest);
701  expandTildeExpr(dest);
702}
703
704static file_type typeForMode(mode_t Mode) {
705  if (S_ISDIR(Mode))
706    return file_type::directory_file;
707  else if (S_ISREG(Mode))
708    return file_type::regular_file;
709  else if (S_ISBLK(Mode))
710    return file_type::block_file;
711  else if (S_ISCHR(Mode))
712    return file_type::character_file;
713  else if (S_ISFIFO(Mode))
714    return file_type::fifo_file;
715  else if (S_ISSOCK(Mode))
716    return file_type::socket_file;
717  else if (S_ISLNK(Mode))
718    return file_type::symlink_file;
719  return file_type::type_unknown;
720}
721
722static std::error_code fillStatus(int StatRet, const struct stat &Status,
723                                  file_status &Result) {
724  if (StatRet != 0) {
725    std::error_code EC(errno, std::generic_category());
726    if (EC == errc::no_such_file_or_directory)
727      Result = file_status(file_type::file_not_found);
728    else
729      Result = file_status(file_type::status_error);
730    return EC;
731  }
732
733  uint32_t atime_nsec, mtime_nsec;
734#if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
735  atime_nsec = Status.st_atimespec.tv_nsec;
736  mtime_nsec = Status.st_mtimespec.tv_nsec;
737#elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
738  atime_nsec = Status.st_atim.tv_nsec;
739  mtime_nsec = Status.st_mtim.tv_nsec;
740#else
741  atime_nsec = mtime_nsec = 0;
742#endif
743
744  perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
745  Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev,
746                       Status.st_nlink, Status.st_ino,
747                       Status.st_atime, atime_nsec, Status.st_mtime, mtime_nsec,
748                       Status.st_uid, Status.st_gid, Status.st_size);
749
750  return std::error_code();
751}
752
753std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
754  SmallString<128> PathStorage;
755  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
756
757  struct stat Status;
758  int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
759  return fillStatus(StatRet, Status, Result);
760}
761
762std::error_code status(int FD, file_status &Result) {
763  struct stat Status;
764  int StatRet = ::fstat(FD, &Status);
765  return fillStatus(StatRet, Status, Result);
766}
767
768unsigned getUmask() {
769  // Chose arbitary new mask and reset the umask to the old mask.
770  // umask(2) never fails so ignore the return of the second call.
771  unsigned Mask = ::umask(0);
772  (void) ::umask(Mask);
773  return Mask;
774}
775
776std::error_code setPermissions(const Twine &Path, perms Permissions) {
777  SmallString<128> PathStorage;
778  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
779
780  if (::chmod(P.begin(), Permissions))
781    return std::error_code(errno, std::generic_category());
782  return std::error_code();
783}
784
785std::error_code setPermissions(int FD, perms Permissions) {
786  if (::fchmod(FD, Permissions))
787    return std::error_code(errno, std::generic_category());
788  return std::error_code();
789}
790
791std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
792                                                 TimePoint<> ModificationTime) {
793#if defined(HAVE_FUTIMENS)
794  timespec Times[2];
795  Times[0] = sys::toTimeSpec(AccessTime);
796  Times[1] = sys::toTimeSpec(ModificationTime);
797  if (::futimens(FD, Times))
798    return std::error_code(errno, std::generic_category());
799  return std::error_code();
800#elif defined(HAVE_FUTIMES)
801  timeval Times[2];
802  Times[0] = sys::toTimeVal(
803      std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
804  Times[1] =
805      sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
806          ModificationTime));
807  if (::futimes(FD, Times))
808    return std::error_code(errno, std::generic_category());
809  return std::error_code();
810#elif defined(__MVS__)
811  attrib_t Attr;
812  memset(&Attr, 0, sizeof(Attr));
813  Attr.att_atimechg = 1;
814  Attr.att_atime = sys::toTimeT(AccessTime);
815  Attr.att_mtimechg = 1;
816  Attr.att_mtime = sys::toTimeT(ModificationTime);
817  if (::__fchattr(FD, &Attr, sizeof(Attr)) != 0)
818    return std::error_code(errno, std::generic_category());
819  return std::error_code();
820#else
821#warning Missing futimes() and futimens()
822  return make_error_code(errc::function_not_supported);
823#endif
824}
825
826std::error_code mapped_file_region::init(int FD, uint64_t Offset,
827                                         mapmode Mode) {
828  assert(Size != 0);
829
830  int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
831  int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
832#if defined(MAP_NORESERVE)
833  flags |= MAP_NORESERVE;
834#endif
835#if defined(__APPLE__)
836  //----------------------------------------------------------------------
837  // Newer versions of MacOSX have a flag that will allow us to read from
838  // binaries whose code signature is invalid without crashing by using
839  // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
840  // is mapped we can avoid crashing and return zeroes to any pages we try
841  // to read if the media becomes unavailable by using the
842  // MAP_RESILIENT_MEDIA flag.  These flags are only usable when mapping
843  // with PROT_READ, so take care not to specify them otherwise.
844  //----------------------------------------------------------------------
845  if (Mode == readonly) {
846#if defined(MAP_RESILIENT_CODESIGN)
847    flags |= MAP_RESILIENT_CODESIGN;
848#endif
849#if defined(MAP_RESILIENT_MEDIA)
850    flags |= MAP_RESILIENT_MEDIA;
851#endif
852  }
853#endif // #if defined (__APPLE__)
854
855  Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
856  if (Mapping == MAP_FAILED)
857    return std::error_code(errno, std::generic_category());
858  return std::error_code();
859}
860
861mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
862                                       uint64_t offset, std::error_code &ec)
863    : Size(length), Mode(mode) {
864  (void)Mode;
865  ec = init(fd, offset, mode);
866  if (ec)
867    copyFrom(mapped_file_region());
868}
869
870void mapped_file_region::unmapImpl() {
871  if (Mapping)
872    ::munmap(Mapping, Size);
873}
874
875void mapped_file_region::dontNeedImpl() {
876  assert(Mode == mapped_file_region::readonly);
877  if (!Mapping)
878      return;
879#if defined(__MVS__) || defined(_AIX)
880  // If we don't have madvise, or it isn't beneficial, treat this as a no-op.
881#elif defined(POSIX_MADV_DONTNEED)
882  ::posix_madvise(Mapping, Size, POSIX_MADV_DONTNEED);
883#else
884  ::madvise(Mapping, Size, MADV_DONTNEED);
885#endif
886}
887
888int mapped_file_region::alignment() {
889  return Process::getPageSizeEstimate();
890}
891
892std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
893                                                     StringRef path,
894                                                     bool follow_symlinks) {
895  SmallString<128> path_null(path);
896  DIR *directory = ::opendir(path_null.c_str());
897  if (!directory)
898    return std::error_code(errno, std::generic_category());
899
900  it.IterationHandle = reinterpret_cast<intptr_t>(directory);
901  // Add something for replace_filename to replace.
902  path::append(path_null, ".");
903  it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
904  return directory_iterator_increment(it);
905}
906
907std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
908  if (it.IterationHandle)
909    ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
910  it.IterationHandle = 0;
911  it.CurrentEntry = directory_entry();
912  return std::error_code();
913}
914
915static file_type direntType(dirent* Entry) {
916  // Most platforms provide the file type in the dirent: Linux/BSD/Mac.
917  // The DTTOIF macro lets us reuse our status -> type conversion.
918  // Note that while glibc provides a macro to see if this is supported,
919  // _DIRENT_HAVE_D_TYPE, it's not defined on BSD/Mac, so we test for the
920  // d_type-to-mode_t conversion macro instead.
921#if defined(DTTOIF)
922  return typeForMode(DTTOIF(Entry->d_type));
923#else
924  // Other platforms such as Solaris require a stat() to get the type.
925  return file_type::type_unknown;
926#endif
927}
928
929std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
930  errno = 0;
931  dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));
932  if (CurDir == nullptr && errno != 0) {
933    return std::error_code(errno, std::generic_category());
934  } else if (CurDir != nullptr) {
935    StringRef Name(CurDir->d_name);
936    if ((Name.size() == 1 && Name[0] == '.') ||
937        (Name.size() == 2 && Name[0] == '.' && Name[1] == '.'))
938      return directory_iterator_increment(It);
939    It.CurrentEntry.replace_filename(Name, direntType(CurDir));
940  } else
941    return directory_iterator_destruct(It);
942
943  return std::error_code();
944}
945
946ErrorOr<basic_file_status> directory_entry::status() const {
947  file_status s;
948  if (auto EC = fs::status(Path, s, FollowSymlinks))
949    return EC;
950  return s;
951}
952
953//
954// FreeBSD optionally provides /proc/self/fd, but it is incompatible with
955// Linux. The thing to use is realpath.
956//
957#if !defined(__FreeBSD__)
958#define TRY_PROC_SELF_FD
959#endif
960
961#if !defined(F_GETPATH) && defined(TRY_PROC_SELF_FD)
962static bool hasProcSelfFD() {
963  // If we have a /proc filesystem mounted, we can quickly establish the
964  // real name of the file with readlink
965  static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
966  return Result;
967}
968#endif
969
970static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
971                           FileAccess Access) {
972  int Result = 0;
973  if (Access == FA_Read)
974    Result |= O_RDONLY;
975  else if (Access == FA_Write)
976    Result |= O_WRONLY;
977  else if (Access == (FA_Read | FA_Write))
978    Result |= O_RDWR;
979
980  // This is for compatibility with old code that assumed OF_Append implied
981  // would open an existing file.  See Windows/Path.inc for a longer comment.
982  if (Flags & OF_Append)
983    Disp = CD_OpenAlways;
984
985  if (Disp == CD_CreateNew) {
986    Result |= O_CREAT; // Create if it doesn't exist.
987    Result |= O_EXCL;  // Fail if it does.
988  } else if (Disp == CD_CreateAlways) {
989    Result |= O_CREAT; // Create if it doesn't exist.
990    Result |= O_TRUNC; // Truncate if it does.
991  } else if (Disp == CD_OpenAlways) {
992    Result |= O_CREAT; // Create if it doesn't exist.
993  } else if (Disp == CD_OpenExisting) {
994    // Nothing special, just don't add O_CREAT and we get these semantics.
995  }
996
997// Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
998// calling write(). Instead we need to use lseek() to set offset to EOF after
999// open().
1000#ifndef __MVS__
1001  if (Flags & OF_Append)
1002    Result |= O_APPEND;
1003#endif
1004
1005#ifdef O_CLOEXEC
1006  if (!(Flags & OF_ChildInherit))
1007    Result |= O_CLOEXEC;
1008#endif
1009
1010  return Result;
1011}
1012
1013std::error_code openFile(const Twine &Name, int &ResultFD,
1014                         CreationDisposition Disp, FileAccess Access,
1015                         OpenFlags Flags, unsigned Mode) {
1016  int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
1017
1018  SmallString<128> Storage;
1019  StringRef P = Name.toNullTerminatedStringRef(Storage);
1020  // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
1021  // when open is overloaded, such as in Bionic.
1022  auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
1023  if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
1024    return std::error_code(errno, std::generic_category());
1025#ifndef O_CLOEXEC
1026  if (!(Flags & OF_ChildInherit)) {
1027    int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
1028    (void)r;
1029    assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
1030  }
1031#endif
1032
1033#ifdef __MVS__
1034  /* Reason about auto-conversion and file tags. Setting the file tag only
1035   * applies if file is opened in write mode:
1036   *
1037   * Text file:
1038   *                  File exists       File created
1039   * CD_CreateNew     n/a               conv: on
1040   *                                    tag: set 1047
1041   * CD_CreateAlways  conv: auto        conv: on
1042   *                  tag: auto 1047    tag: set 1047
1043   * CD_OpenAlways    conv: auto        conv: on
1044   *                  tag: auto 1047    tag: set 1047
1045   * CD_OpenExisting  conv: auto        n/a
1046   *                  tag: unchanged
1047   *
1048   * Binary file:
1049   *                  File exists       File created
1050   * CD_CreateNew     n/a               conv: off
1051   *                                    tag: set binary
1052   * CD_CreateAlways  conv: off         conv: off
1053   *                  tag: auto binary  tag: set binary
1054   * CD_OpenAlways    conv: off         conv: off
1055   *                  tag: auto binary  tag: set binary
1056   * CD_OpenExisting  conv: off         n/a
1057   *                  tag: unchanged
1058   *
1059   * Actions:
1060   *   conv: off        -> auto-conversion is turned off
1061   *   conv: on         -> auto-conversion is turned on
1062   *   conv: auto       -> auto-conversion is turned on if the file is untagged
1063   *   tag: set 1047    -> set the file tag to text encoded in 1047
1064   *   tag: set binary  -> set the file tag to binary
1065   *   tag: auto 1047   -> set file tag to 1047 if not set
1066   *   tag: auto binary -> set file tag to binary if not set
1067   *   tag: unchanged   -> do not care about the file tag
1068   *
1069   * It is not possible to distinguish between the cases "file exists" and
1070   * "file created". In the latter case, the file tag is not set and the file
1071   * size is zero. The decision table boils down to:
1072   *
1073   * the file tag is set if
1074   *   - the file is opened for writing
1075   *   - the create disposition is not equal to CD_OpenExisting
1076   *   - the file tag is not set
1077   *   - the file size is zero
1078   *
1079   * This only applies if the file is a regular file. E.g. enabling
1080   * auto-conversion for reading from /dev/null results in error EINVAL when
1081   * calling read().
1082   *
1083   * Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
1084   * calling write(). Instead we need to use lseek() to set offset to EOF after
1085   * open().
1086   */
1087  if ((Flags & OF_Append) && lseek(ResultFD, 0, SEEK_END) == -1)
1088    return std::error_code(errno, std::generic_category());
1089  struct stat Stat;
1090  if (fstat(ResultFD, &Stat) == -1)
1091    return std::error_code(errno, std::generic_category());
1092  if (S_ISREG(Stat.st_mode)) {
1093    bool DoSetTag = (Access & FA_Write) && (Disp != CD_OpenExisting) &&
1094                    !Stat.st_tag.ft_txtflag && !Stat.st_tag.ft_ccsid &&
1095                    Stat.st_size == 0;
1096    if (Flags & OF_Text) {
1097      if (auto EC = llvm::enableAutoConversion(ResultFD))
1098        return EC;
1099      if (DoSetTag) {
1100        if (auto EC = llvm::setFileTag(ResultFD, CCSID_IBM_1047, true))
1101          return EC;
1102      }
1103    } else {
1104      if (auto EC = llvm::disableAutoConversion(ResultFD))
1105        return EC;
1106      if (DoSetTag) {
1107        if (auto EC = llvm::setFileTag(ResultFD, FT_BINARY, false))
1108          return EC;
1109      }
1110    }
1111  }
1112#endif
1113
1114  return std::error_code();
1115}
1116
1117Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,
1118                             FileAccess Access, OpenFlags Flags,
1119                             unsigned Mode) {
1120
1121  int FD;
1122  std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
1123  if (EC)
1124    return errorCodeToError(EC);
1125  return FD;
1126}
1127
1128std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1129                                OpenFlags Flags,
1130                                SmallVectorImpl<char> *RealPath) {
1131  std::error_code EC =
1132      openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
1133  if (EC)
1134    return EC;
1135
1136  // Attempt to get the real name of the file, if the user asked
1137  if(!RealPath)
1138    return std::error_code();
1139  RealPath->clear();
1140#if defined(F_GETPATH)
1141  // When F_GETPATH is availble, it is the quickest way to get
1142  // the real path name.
1143  char Buffer[PATH_MAX];
1144  if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
1145    RealPath->append(Buffer, Buffer + strlen(Buffer));
1146#else
1147  char Buffer[PATH_MAX];
1148#if defined(TRY_PROC_SELF_FD)
1149  if (hasProcSelfFD()) {
1150    char ProcPath[64];
1151    snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
1152    ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
1153    if (CharCount > 0)
1154      RealPath->append(Buffer, Buffer + CharCount);
1155  } else {
1156#endif
1157    SmallString<128> Storage;
1158    StringRef P = Name.toNullTerminatedStringRef(Storage);
1159
1160    // Use ::realpath to get the real path name
1161    if (::realpath(P.begin(), Buffer) != nullptr)
1162      RealPath->append(Buffer, Buffer + strlen(Buffer));
1163#if defined(TRY_PROC_SELF_FD)
1164  }
1165#endif
1166#endif
1167  return std::error_code();
1168}
1169
1170Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1171                                       SmallVectorImpl<char> *RealPath) {
1172  file_t ResultFD;
1173  std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
1174  if (EC)
1175    return errorCodeToError(EC);
1176  return ResultFD;
1177}
1178
1179file_t getStdinHandle() { return 0; }
1180file_t getStdoutHandle() { return 1; }
1181file_t getStderrHandle() { return 2; }
1182
1183Expected<size_t> readNativeFile(file_t FD, MutableArrayRef<char> Buf) {
1184#if defined(__APPLE__)
1185  size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
1186#else
1187  size_t Size = Buf.size();
1188#endif
1189  ssize_t NumRead =
1190      sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
1191  if (ssize_t(NumRead) == -1)
1192    return errorCodeToError(std::error_code(errno, std::generic_category()));
1193  return NumRead;
1194}
1195
1196Expected<size_t> readNativeFileSlice(file_t FD, MutableArrayRef<char> Buf,
1197                                     uint64_t Offset) {
1198#if defined(__APPLE__)
1199  size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
1200#else
1201  size_t Size = Buf.size();
1202#endif
1203#ifdef HAVE_PREAD
1204  ssize_t NumRead =
1205      sys::RetryAfterSignal(-1, ::pread, FD, Buf.data(), Size, Offset);
1206#else
1207  if (lseek(FD, Offset, SEEK_SET) == -1)
1208    return errorCodeToError(std::error_code(errno, std::generic_category()));
1209  ssize_t NumRead =
1210      sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
1211#endif
1212  if (NumRead == -1)
1213    return errorCodeToError(std::error_code(errno, std::generic_category()));
1214  return NumRead;
1215}
1216
1217std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout) {
1218  auto Start = std::chrono::steady_clock::now();
1219  auto End = Start + Timeout;
1220  do {
1221    struct flock Lock;
1222    memset(&Lock, 0, sizeof(Lock));
1223    Lock.l_type = F_WRLCK;
1224    Lock.l_whence = SEEK_SET;
1225    Lock.l_start = 0;
1226    Lock.l_len = 0;
1227    if (::fcntl(FD, F_SETLK, &Lock) != -1)
1228      return std::error_code();
1229    int Error = errno;
1230    if (Error != EACCES && Error != EAGAIN)
1231      return std::error_code(Error, std::generic_category());
1232    usleep(1000);
1233  } while (std::chrono::steady_clock::now() < End);
1234  return make_error_code(errc::no_lock_available);
1235}
1236
1237std::error_code lockFile(int FD) {
1238  struct flock Lock;
1239  memset(&Lock, 0, sizeof(Lock));
1240  Lock.l_type = F_WRLCK;
1241  Lock.l_whence = SEEK_SET;
1242  Lock.l_start = 0;
1243  Lock.l_len = 0;
1244  if (::fcntl(FD, F_SETLKW, &Lock) != -1)
1245    return std::error_code();
1246  int Error = errno;
1247  return std::error_code(Error, std::generic_category());
1248}
1249
1250std::error_code unlockFile(int FD) {
1251  struct flock Lock;
1252  Lock.l_type = F_UNLCK;
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  return std::error_code(errno, std::generic_category());
1259}
1260
1261std::error_code closeFile(file_t &F) {
1262  file_t TmpF = F;
1263  F = kInvalidFile;
1264  return Process::SafelyCloseFileDescriptor(TmpF);
1265}
1266
1267template <typename T>
1268static std::error_code remove_directories_impl(const T &Entry,
1269                                               bool IgnoreErrors) {
1270  std::error_code EC;
1271  directory_iterator Begin(Entry, EC, false);
1272  directory_iterator End;
1273  while (Begin != End) {
1274    auto &Item = *Begin;
1275    ErrorOr<basic_file_status> st = Item.status();
1276    if (!st && !IgnoreErrors)
1277      return st.getError();
1278
1279    if (is_directory(*st)) {
1280      EC = remove_directories_impl(Item, IgnoreErrors);
1281      if (EC && !IgnoreErrors)
1282        return EC;
1283    }
1284
1285    EC = fs::remove(Item.path(), true);
1286    if (EC && !IgnoreErrors)
1287      return EC;
1288
1289    Begin.increment(EC);
1290    if (EC && !IgnoreErrors)
1291      return EC;
1292  }
1293  return std::error_code();
1294}
1295
1296std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1297  auto EC = remove_directories_impl(path, IgnoreErrors);
1298  if (EC && !IgnoreErrors)
1299    return EC;
1300  EC = fs::remove(path, true);
1301  if (EC && !IgnoreErrors)
1302    return EC;
1303  return std::error_code();
1304}
1305
1306std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1307                          bool expand_tilde) {
1308  dest.clear();
1309  if (path.isTriviallyEmpty())
1310    return std::error_code();
1311
1312  if (expand_tilde) {
1313    SmallString<128> Storage;
1314    path.toVector(Storage);
1315    expandTildeExpr(Storage);
1316    return real_path(Storage, dest, false);
1317  }
1318
1319  SmallString<128> Storage;
1320  StringRef P = path.toNullTerminatedStringRef(Storage);
1321  char Buffer[PATH_MAX];
1322  if (::realpath(P.begin(), Buffer) == nullptr)
1323    return std::error_code(errno, std::generic_category());
1324  dest.append(Buffer, Buffer + strlen(Buffer));
1325  return std::error_code();
1326}
1327
1328std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group) {
1329  auto FChown = [&]() { return ::fchown(FD, Owner, Group); };
1330  // Retry if fchown call fails due to interruption.
1331  if ((sys::RetryAfterSignal(-1, FChown)) < 0)
1332    return std::error_code(errno, std::generic_category());
1333  return std::error_code();
1334}
1335
1336} // end namespace fs
1337
1338namespace path {
1339
1340bool home_directory(SmallVectorImpl<char> &result) {
1341  char *RequestedDir = getenv("HOME");
1342  if (!RequestedDir) {
1343    struct passwd *pw = getpwuid(getuid());
1344    if (pw && pw->pw_dir)
1345      RequestedDir = pw->pw_dir;
1346  }
1347  if (!RequestedDir)
1348    return false;
1349
1350  result.clear();
1351  result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1352  return true;
1353}
1354
1355static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
1356  #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
1357  // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
1358  // macros defined in <unistd.h> on darwin >= 9
1359  int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
1360                         : _CS_DARWIN_USER_CACHE_DIR;
1361  size_t ConfLen = confstr(ConfName, nullptr, 0);
1362  if (ConfLen > 0) {
1363    do {
1364      Result.resize(ConfLen);
1365      ConfLen = confstr(ConfName, Result.data(), Result.size());
1366    } while (ConfLen > 0 && ConfLen != Result.size());
1367
1368    if (ConfLen > 0) {
1369      assert(Result.back() == 0);
1370      Result.pop_back();
1371      return true;
1372    }
1373
1374    Result.clear();
1375  }
1376  #endif
1377  return false;
1378}
1379
1380bool user_config_directory(SmallVectorImpl<char> &result) {
1381#ifdef __APPLE__
1382  // Mac: ~/Library/Preferences/
1383  if (home_directory(result)) {
1384    append(result, "Library", "Preferences");
1385    return true;
1386  }
1387#else
1388  // XDG_CONFIG_HOME as defined in the XDG Base Directory Specification:
1389  // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1390  if (const char *RequestedDir = getenv("XDG_CONFIG_HOME")) {
1391    result.clear();
1392    result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1393    return true;
1394  }
1395#endif
1396  // Fallback: ~/.config
1397  if (!home_directory(result)) {
1398    return false;
1399  }
1400  append(result, ".config");
1401  return true;
1402}
1403
1404bool cache_directory(SmallVectorImpl<char> &result) {
1405#ifdef __APPLE__
1406  if (getDarwinConfDir(false/*tempDir*/, result)) {
1407    return true;
1408  }
1409#else
1410  // XDG_CACHE_HOME as defined in the XDG Base Directory Specification:
1411  // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1412  if (const char *RequestedDir = getenv("XDG_CACHE_HOME")) {
1413    result.clear();
1414    result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1415    return true;
1416  }
1417#endif
1418  if (!home_directory(result)) {
1419    return false;
1420  }
1421  append(result, ".cache");
1422  return true;
1423}
1424
1425static const char *getEnvTempDir() {
1426  // Check whether the temporary directory is specified by an environment
1427  // variable.
1428  const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1429  for (const char *Env : EnvironmentVariables) {
1430    if (const char *Dir = std::getenv(Env))
1431      return Dir;
1432  }
1433
1434  return nullptr;
1435}
1436
1437static const char *getDefaultTempDir(bool ErasedOnReboot) {
1438#ifdef P_tmpdir
1439  if ((bool)P_tmpdir)
1440    return P_tmpdir;
1441#endif
1442
1443  if (ErasedOnReboot)
1444    return "/tmp";
1445  return "/var/tmp";
1446}
1447
1448void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1449  Result.clear();
1450
1451  if (ErasedOnReboot) {
1452    // There is no env variable for the cache directory.
1453    if (const char *RequestedDir = getEnvTempDir()) {
1454      Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1455      return;
1456    }
1457  }
1458
1459  if (getDarwinConfDir(ErasedOnReboot, Result))
1460    return;
1461
1462  const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1463  Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1464}
1465
1466} // end namespace path
1467
1468namespace fs {
1469
1470#ifdef __APPLE__
1471/// This implementation tries to perform an APFS CoW clone of the file,
1472/// which can be much faster and uses less space.
1473/// Unfortunately fcopyfile(3) does not support COPYFILE_CLONE, so the
1474/// file descriptor variant of this function still uses the default
1475/// implementation.
1476std::error_code copy_file(const Twine &From, const Twine &To) {
1477  std::string FromS = From.str();
1478  std::string ToS = To.str();
1479#if __has_builtin(__builtin_available)
1480  if (__builtin_available(macos 10.12, *)) {
1481    // Optimistically try to use clonefile() and handle errors, rather than
1482    // calling stat() to see if it'll work.
1483    //
1484    // Note: It's okay if From is a symlink. In contrast to the behaviour of
1485    // copyfile() with COPYFILE_CLONE, clonefile() clones targets (not the
1486    // symlink itself) unless the flag CLONE_NOFOLLOW is passed.
1487    if (!clonefile(FromS.c_str(), ToS.c_str(), 0))
1488      return std::error_code();
1489
1490    auto Errno = errno;
1491    switch (Errno) {
1492      case EEXIST:  // To already exists.
1493      case ENOTSUP: // Device does not support cloning.
1494      case EXDEV:   // From and To are on different devices.
1495        break;
1496      default:
1497        // Anything else will also break copyfile().
1498        return std::error_code(Errno, std::generic_category());
1499    }
1500
1501    // TODO: For EEXIST, profile calling fs::generateUniqueName() and
1502    // clonefile() in a retry loop (then rename() on success) before falling
1503    // back to copyfile(). Depending on the size of the file this could be
1504    // cheaper.
1505  }
1506#endif
1507  if (!copyfile(FromS.c_str(), ToS.c_str(), /*State=*/NULL, COPYFILE_DATA))
1508    return std::error_code();
1509  return std::error_code(errno, std::generic_category());
1510}
1511#endif // __APPLE__
1512
1513} // end namespace fs
1514
1515} // end namespace sys
1516} // end namespace llvm
1517