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