xref: /freebsd/contrib/llvm-project/llvm/lib/Support/Unix/Path.inc (revision 32a95656b51ebefcdf3e0b02c110825f59abd26f)
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#if !defined(F_GETPATH)
934static bool hasProcSelfFD() {
935  // If we have a /proc filesystem mounted, we can quickly establish the
936  // real name of the file with readlink
937  static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
938  return Result;
939}
940#endif
941
942static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
943                           FileAccess Access) {
944  int Result = 0;
945  if (Access == FA_Read)
946    Result |= O_RDONLY;
947  else if (Access == FA_Write)
948    Result |= O_WRONLY;
949  else if (Access == (FA_Read | FA_Write))
950    Result |= O_RDWR;
951
952  // This is for compatibility with old code that assumed OF_Append implied
953  // would open an existing file.  See Windows/Path.inc for a longer comment.
954  if (Flags & OF_Append)
955    Disp = CD_OpenAlways;
956
957  if (Disp == CD_CreateNew) {
958    Result |= O_CREAT; // Create if it doesn't exist.
959    Result |= O_EXCL;  // Fail if it does.
960  } else if (Disp == CD_CreateAlways) {
961    Result |= O_CREAT; // Create if it doesn't exist.
962    Result |= O_TRUNC; // Truncate if it does.
963  } else if (Disp == CD_OpenAlways) {
964    Result |= O_CREAT; // Create if it doesn't exist.
965  } else if (Disp == CD_OpenExisting) {
966    // Nothing special, just don't add O_CREAT and we get these semantics.
967  }
968
969// Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
970// calling write(). Instead we need to use lseek() to set offset to EOF after
971// open().
972#ifndef __MVS__
973  if (Flags & OF_Append)
974    Result |= O_APPEND;
975#endif
976
977#ifdef O_CLOEXEC
978  if (!(Flags & OF_ChildInherit))
979    Result |= O_CLOEXEC;
980#endif
981
982  return Result;
983}
984
985std::error_code openFile(const Twine &Name, int &ResultFD,
986                         CreationDisposition Disp, FileAccess Access,
987                         OpenFlags Flags, unsigned Mode) {
988  int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
989
990  SmallString<128> Storage;
991  StringRef P = Name.toNullTerminatedStringRef(Storage);
992  // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
993  // when open is overloaded, such as in Bionic.
994  auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
995  if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
996    return std::error_code(errno, std::generic_category());
997#ifndef O_CLOEXEC
998  if (!(Flags & OF_ChildInherit)) {
999    int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
1000    (void)r;
1001    assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
1002  }
1003#endif
1004
1005#ifdef __MVS__
1006  /* Reason about auto-conversion and file tags. Setting the file tag only
1007   * applies if file is opened in write mode:
1008   *
1009   * Text file:
1010   *                  File exists       File created
1011   * CD_CreateNew     n/a               conv: on
1012   *                                    tag: set 1047
1013   * CD_CreateAlways  conv: auto        conv: on
1014   *                  tag: auto 1047    tag: set 1047
1015   * CD_OpenAlways    conv: auto        conv: on
1016   *                  tag: auto 1047    tag: set 1047
1017   * CD_OpenExisting  conv: auto        n/a
1018   *                  tag: unchanged
1019   *
1020   * Binary file:
1021   *                  File exists       File created
1022   * CD_CreateNew     n/a               conv: off
1023   *                                    tag: set binary
1024   * CD_CreateAlways  conv: off         conv: off
1025   *                  tag: auto binary  tag: set binary
1026   * CD_OpenAlways    conv: off         conv: off
1027   *                  tag: auto binary  tag: set binary
1028   * CD_OpenExisting  conv: off         n/a
1029   *                  tag: unchanged
1030   *
1031   * Actions:
1032   *   conv: off        -> auto-conversion is turned off
1033   *   conv: on         -> auto-conversion is turned on
1034   *   conv: auto       -> auto-conversion is turned on if the file is untagged
1035   *   tag: set 1047    -> set the file tag to text encoded in 1047
1036   *   tag: set binary  -> set the file tag to binary
1037   *   tag: auto 1047   -> set file tag to 1047 if not set
1038   *   tag: auto binary -> set file tag to binary if not set
1039   *   tag: unchanged   -> do not care about the file tag
1040   *
1041   * It is not possible to distinguish between the cases "file exists" and
1042   * "file created". In the latter case, the file tag is not set and the file
1043   * size is zero. The decision table boils down to:
1044   *
1045   * the file tag is set if
1046   *   - the file is opened for writing
1047   *   - the create disposition is not equal to CD_OpenExisting
1048   *   - the file tag is not set
1049   *   - the file size is zero
1050   *
1051   * This only applies if the file is a regular file. E.g. enabling
1052   * auto-conversion for reading from /dev/null results in error EINVAL when
1053   * calling read().
1054   *
1055   * Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
1056   * calling write(). Instead we need to use lseek() to set offset to EOF after
1057   * open().
1058   */
1059  if ((Flags & OF_Append) && lseek(ResultFD, 0, SEEK_END) == -1)
1060    return std::error_code(errno, std::generic_category());
1061  struct stat Stat;
1062  if (fstat(ResultFD, &Stat) == -1)
1063    return std::error_code(errno, std::generic_category());
1064  if (S_ISREG(Stat.st_mode)) {
1065    bool DoSetTag = (Access & FA_Write) && (Disp != CD_OpenExisting) &&
1066                    !Stat.st_tag.ft_txtflag && !Stat.st_tag.ft_ccsid &&
1067                    Stat.st_size == 0;
1068    if (Flags & OF_Text) {
1069      if (auto EC = llvm::enableAutoConversion(ResultFD))
1070        return EC;
1071      if (DoSetTag) {
1072        if (auto EC = llvm::setFileTag(ResultFD, CCSID_IBM_1047, true))
1073          return EC;
1074      }
1075    } else {
1076      if (auto EC = llvm::disableAutoConversion(ResultFD))
1077        return EC;
1078      if (DoSetTag) {
1079        if (auto EC = llvm::setFileTag(ResultFD, FT_BINARY, false))
1080          return EC;
1081      }
1082    }
1083  }
1084#endif
1085
1086  return std::error_code();
1087}
1088
1089Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,
1090                             FileAccess Access, OpenFlags Flags,
1091                             unsigned Mode) {
1092
1093  int FD;
1094  std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
1095  if (EC)
1096    return errorCodeToError(EC);
1097  return FD;
1098}
1099
1100std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1101                                OpenFlags Flags,
1102                                SmallVectorImpl<char> *RealPath) {
1103  std::error_code EC =
1104      openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
1105  if (EC)
1106    return EC;
1107
1108  // Attempt to get the real name of the file, if the user asked
1109  if(!RealPath)
1110    return std::error_code();
1111  RealPath->clear();
1112#if defined(F_GETPATH)
1113  // When F_GETPATH is availble, it is the quickest way to get
1114  // the real path name.
1115  char Buffer[PATH_MAX];
1116  if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
1117    RealPath->append(Buffer, Buffer + strlen(Buffer));
1118#else
1119  char Buffer[PATH_MAX];
1120  if (hasProcSelfFD()) {
1121    char ProcPath[64];
1122    snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
1123    ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
1124    if (CharCount > 0)
1125      RealPath->append(Buffer, Buffer + CharCount);
1126  } else {
1127    SmallString<128> Storage;
1128    StringRef P = Name.toNullTerminatedStringRef(Storage);
1129
1130    // Use ::realpath to get the real path name
1131    if (::realpath(P.begin(), Buffer) != nullptr)
1132      RealPath->append(Buffer, Buffer + strlen(Buffer));
1133  }
1134#endif
1135  return std::error_code();
1136}
1137
1138Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1139                                       SmallVectorImpl<char> *RealPath) {
1140  file_t ResultFD;
1141  std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
1142  if (EC)
1143    return errorCodeToError(EC);
1144  return ResultFD;
1145}
1146
1147file_t getStdinHandle() { return 0; }
1148file_t getStdoutHandle() { return 1; }
1149file_t getStderrHandle() { return 2; }
1150
1151Expected<size_t> readNativeFile(file_t FD, MutableArrayRef<char> Buf) {
1152#if defined(__APPLE__)
1153  size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
1154#else
1155  size_t Size = Buf.size();
1156#endif
1157  ssize_t NumRead =
1158      sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
1159  if (ssize_t(NumRead) == -1)
1160    return errorCodeToError(std::error_code(errno, std::generic_category()));
1161  return NumRead;
1162}
1163
1164Expected<size_t> readNativeFileSlice(file_t FD, MutableArrayRef<char> Buf,
1165                                     uint64_t Offset) {
1166#if defined(__APPLE__)
1167  size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
1168#else
1169  size_t Size = Buf.size();
1170#endif
1171#ifdef HAVE_PREAD
1172  ssize_t NumRead =
1173      sys::RetryAfterSignal(-1, ::pread, FD, Buf.data(), Size, Offset);
1174#else
1175  if (lseek(FD, Offset, SEEK_SET) == -1)
1176    return errorCodeToError(std::error_code(errno, std::generic_category()));
1177  ssize_t NumRead =
1178      sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
1179#endif
1180  if (NumRead == -1)
1181    return errorCodeToError(std::error_code(errno, std::generic_category()));
1182  return NumRead;
1183}
1184
1185std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout) {
1186  auto Start = std::chrono::steady_clock::now();
1187  auto End = Start + Timeout;
1188  do {
1189    struct flock Lock;
1190    memset(&Lock, 0, sizeof(Lock));
1191    Lock.l_type = F_WRLCK;
1192    Lock.l_whence = SEEK_SET;
1193    Lock.l_start = 0;
1194    Lock.l_len = 0;
1195    if (::fcntl(FD, F_SETLK, &Lock) != -1)
1196      return std::error_code();
1197    int Error = errno;
1198    if (Error != EACCES && Error != EAGAIN)
1199      return std::error_code(Error, std::generic_category());
1200    usleep(1000);
1201  } while (std::chrono::steady_clock::now() < End);
1202  return make_error_code(errc::no_lock_available);
1203}
1204
1205std::error_code lockFile(int FD) {
1206  struct flock Lock;
1207  memset(&Lock, 0, sizeof(Lock));
1208  Lock.l_type = F_WRLCK;
1209  Lock.l_whence = SEEK_SET;
1210  Lock.l_start = 0;
1211  Lock.l_len = 0;
1212  if (::fcntl(FD, F_SETLKW, &Lock) != -1)
1213    return std::error_code();
1214  int Error = errno;
1215  return std::error_code(Error, std::generic_category());
1216}
1217
1218std::error_code unlockFile(int FD) {
1219  struct flock Lock;
1220  Lock.l_type = F_UNLCK;
1221  Lock.l_whence = SEEK_SET;
1222  Lock.l_start = 0;
1223  Lock.l_len = 0;
1224  if (::fcntl(FD, F_SETLK, &Lock) != -1)
1225    return std::error_code();
1226  return std::error_code(errno, std::generic_category());
1227}
1228
1229std::error_code closeFile(file_t &F) {
1230  file_t TmpF = F;
1231  F = kInvalidFile;
1232  return Process::SafelyCloseFileDescriptor(TmpF);
1233}
1234
1235template <typename T>
1236static std::error_code remove_directories_impl(const T &Entry,
1237                                               bool IgnoreErrors) {
1238  std::error_code EC;
1239  directory_iterator Begin(Entry, EC, false);
1240  directory_iterator End;
1241  while (Begin != End) {
1242    auto &Item = *Begin;
1243    ErrorOr<basic_file_status> st = Item.status();
1244    if (!st && !IgnoreErrors)
1245      return st.getError();
1246
1247    if (is_directory(*st)) {
1248      EC = remove_directories_impl(Item, IgnoreErrors);
1249      if (EC && !IgnoreErrors)
1250        return EC;
1251    }
1252
1253    EC = fs::remove(Item.path(), true);
1254    if (EC && !IgnoreErrors)
1255      return EC;
1256
1257    Begin.increment(EC);
1258    if (EC && !IgnoreErrors)
1259      return EC;
1260  }
1261  return std::error_code();
1262}
1263
1264std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1265  auto EC = remove_directories_impl(path, IgnoreErrors);
1266  if (EC && !IgnoreErrors)
1267    return EC;
1268  EC = fs::remove(path, true);
1269  if (EC && !IgnoreErrors)
1270    return EC;
1271  return std::error_code();
1272}
1273
1274std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1275                          bool expand_tilde) {
1276  dest.clear();
1277  if (path.isTriviallyEmpty())
1278    return std::error_code();
1279
1280  if (expand_tilde) {
1281    SmallString<128> Storage;
1282    path.toVector(Storage);
1283    expandTildeExpr(Storage);
1284    return real_path(Storage, dest, false);
1285  }
1286
1287  SmallString<128> Storage;
1288  StringRef P = path.toNullTerminatedStringRef(Storage);
1289  char Buffer[PATH_MAX];
1290  if (::realpath(P.begin(), Buffer) == nullptr)
1291    return std::error_code(errno, std::generic_category());
1292  dest.append(Buffer, Buffer + strlen(Buffer));
1293  return std::error_code();
1294}
1295
1296std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group) {
1297  auto FChown = [&]() { return ::fchown(FD, Owner, Group); };
1298  // Retry if fchown call fails due to interruption.
1299  if ((sys::RetryAfterSignal(-1, FChown)) < 0)
1300    return std::error_code(errno, std::generic_category());
1301  return std::error_code();
1302}
1303
1304} // end namespace fs
1305
1306namespace path {
1307
1308bool home_directory(SmallVectorImpl<char> &result) {
1309  char *RequestedDir = getenv("HOME");
1310  if (!RequestedDir) {
1311    struct passwd *pw = getpwuid(getuid());
1312    if (pw && pw->pw_dir)
1313      RequestedDir = pw->pw_dir;
1314  }
1315  if (!RequestedDir)
1316    return false;
1317
1318  result.clear();
1319  result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1320  return true;
1321}
1322
1323static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
1324  #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
1325  // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
1326  // macros defined in <unistd.h> on darwin >= 9
1327  int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
1328                         : _CS_DARWIN_USER_CACHE_DIR;
1329  size_t ConfLen = confstr(ConfName, nullptr, 0);
1330  if (ConfLen > 0) {
1331    do {
1332      Result.resize(ConfLen);
1333      ConfLen = confstr(ConfName, Result.data(), Result.size());
1334    } while (ConfLen > 0 && ConfLen != Result.size());
1335
1336    if (ConfLen > 0) {
1337      assert(Result.back() == 0);
1338      Result.pop_back();
1339      return true;
1340    }
1341
1342    Result.clear();
1343  }
1344  #endif
1345  return false;
1346}
1347
1348bool user_config_directory(SmallVectorImpl<char> &result) {
1349#ifdef __APPLE__
1350  // Mac: ~/Library/Preferences/
1351  if (home_directory(result)) {
1352    append(result, "Library", "Preferences");
1353    return true;
1354  }
1355#else
1356  // XDG_CONFIG_HOME as defined in the XDG Base Directory Specification:
1357  // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1358  if (const char *RequestedDir = getenv("XDG_CONFIG_HOME")) {
1359    result.clear();
1360    result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1361    return true;
1362  }
1363#endif
1364  // Fallback: ~/.config
1365  if (!home_directory(result)) {
1366    return false;
1367  }
1368  append(result, ".config");
1369  return true;
1370}
1371
1372bool cache_directory(SmallVectorImpl<char> &result) {
1373#ifdef __APPLE__
1374  if (getDarwinConfDir(false/*tempDir*/, result)) {
1375    return true;
1376  }
1377#else
1378  // XDG_CACHE_HOME as defined in the XDG Base Directory Specification:
1379  // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1380  if (const char *RequestedDir = getenv("XDG_CACHE_HOME")) {
1381    result.clear();
1382    result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1383    return true;
1384  }
1385#endif
1386  if (!home_directory(result)) {
1387    return false;
1388  }
1389  append(result, ".cache");
1390  return true;
1391}
1392
1393static const char *getEnvTempDir() {
1394  // Check whether the temporary directory is specified by an environment
1395  // variable.
1396  const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1397  for (const char *Env : EnvironmentVariables) {
1398    if (const char *Dir = std::getenv(Env))
1399      return Dir;
1400  }
1401
1402  return nullptr;
1403}
1404
1405static const char *getDefaultTempDir(bool ErasedOnReboot) {
1406#ifdef P_tmpdir
1407  if ((bool)P_tmpdir)
1408    return P_tmpdir;
1409#endif
1410
1411  if (ErasedOnReboot)
1412    return "/tmp";
1413  return "/var/tmp";
1414}
1415
1416void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1417  Result.clear();
1418
1419  if (ErasedOnReboot) {
1420    // There is no env variable for the cache directory.
1421    if (const char *RequestedDir = getEnvTempDir()) {
1422      Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1423      return;
1424    }
1425  }
1426
1427  if (getDarwinConfDir(ErasedOnReboot, Result))
1428    return;
1429
1430  const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1431  Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1432}
1433
1434} // end namespace path
1435
1436namespace fs {
1437
1438#ifdef __APPLE__
1439/// This implementation tries to perform an APFS CoW clone of the file,
1440/// which can be much faster and uses less space.
1441/// Unfortunately fcopyfile(3) does not support COPYFILE_CLONE, so the
1442/// file descriptor variant of this function still uses the default
1443/// implementation.
1444std::error_code copy_file(const Twine &From, const Twine &To) {
1445  uint32_t Flag = COPYFILE_DATA;
1446#if __has_builtin(__builtin_available) && defined(COPYFILE_CLONE)
1447  if (__builtin_available(macos 10.12, *)) {
1448    bool IsSymlink;
1449    if (std::error_code Error = is_symlink_file(From, IsSymlink))
1450      return Error;
1451    // COPYFILE_CLONE clones the symlink instead of following it
1452    // and returns EEXISTS if the target file already exists.
1453    if (!IsSymlink && !exists(To))
1454      Flag = COPYFILE_CLONE;
1455  }
1456#endif
1457  int Status =
1458      copyfile(From.str().c_str(), To.str().c_str(), /* State */ NULL, Flag);
1459
1460  if (Status == 0)
1461    return std::error_code();
1462  return std::error_code(errno, std::generic_category());
1463}
1464#endif // __APPLE__
1465
1466} // end namespace fs
1467
1468} // end namespace sys
1469} // end namespace llvm
1470