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