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