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