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