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