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