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