1//===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Unix specific implementation of the Path API.
11//
12//===----------------------------------------------------------------------===//
13
14//===----------------------------------------------------------------------===//
15//=== WARNING: Implementation here must contain only generic UNIX code that
16//===          is guaranteed to work on *all* UNIX variants.
17//===----------------------------------------------------------------------===//
18
19#include "Unix.h"
20#include <limits.h>
21#include <stdio.h>
22#if HAVE_SYS_STAT_H
23#include <sys/stat.h>
24#endif
25#if HAVE_FCNTL_H
26#include <fcntl.h>
27#endif
28#ifdef HAVE_UNISTD_H
29#include <unistd.h>
30#endif
31#ifdef HAVE_SYS_MMAN_H
32#include <sys/mman.h>
33#endif
34#if HAVE_DIRENT_H
35# include <dirent.h>
36# define NAMLEN(dirent) strlen((dirent)->d_name)
37#else
38# define dirent direct
39# define NAMLEN(dirent) (dirent)->d_namlen
40# if HAVE_SYS_NDIR_H
41#  include <sys/ndir.h>
42# endif
43# if HAVE_SYS_DIR_H
44#  include <sys/dir.h>
45# endif
46# if HAVE_NDIR_H
47#  include <ndir.h>
48# endif
49#endif
50
51#include <pwd.h>
52
53#ifdef __APPLE__
54#include <mach-o/dyld.h>
55#include <sys/attr.h>
56#endif
57
58// Both stdio.h and cstdio are included via different paths and
59// stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
60// either.
61#undef ferror
62#undef feof
63
64// For GNU Hurd
65#if defined(__GNU__) && !defined(PATH_MAX)
66# define PATH_MAX 4096
67#endif
68
69#include <sys/types.h>
70#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) &&   \
71    !defined(__linux__)
72#include <sys/statvfs.h>
73#define STATVFS statvfs
74#define FSTATVFS fstatvfs
75#define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
76#else
77#if defined(__OpenBSD__) || defined(__FreeBSD__)
78#include <sys/param.h>
79#include <sys/mount.h>
80#elif defined(__linux__)
81#if defined(HAVE_LINUX_MAGIC_H)
82#include <linux/magic.h>
83#else
84#if defined(HAVE_LINUX_NFS_FS_H)
85#include <linux/nfs_fs.h>
86#endif
87#if defined(HAVE_LINUX_SMB_H)
88#include <linux/smb.h>
89#endif
90#endif
91#include <sys/vfs.h>
92#else
93#include <sys/mount.h>
94#endif
95#define STATVFS statfs
96#define FSTATVFS fstatfs
97#define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
98#endif
99
100#if defined(__NetBSD__)
101#define STATVFS_F_FLAG(vfs) (vfs).f_flag
102#else
103#define STATVFS_F_FLAG(vfs) (vfs).f_flags
104#endif
105
106using namespace llvm;
107
108namespace llvm {
109namespace sys  {
110namespace fs {
111#if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
112    defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
113    defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__) || \
114    defined(_AIX)
115static int
116test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
117{
118  struct stat sb;
119  char fullpath[PATH_MAX];
120
121  snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
122  if (!realpath(fullpath, ret))
123    return 1;
124  if (stat(fullpath, &sb) != 0)
125    return 1;
126
127  return 0;
128}
129
130static char *
131getprogpath(char ret[PATH_MAX], const char *bin)
132{
133  char *pv, *s, *t;
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  if ((pv = getenv("PATH")) == nullptr)
154    return nullptr;
155  s = pv = strdup(pv);
156  if (!pv)
157    return nullptr;
158  while ((t = strsep(&s, ":")) != nullptr) {
159    if (test_dir(ret, t, bin) == 0) {
160      free(pv);
161      return ret;
162    }
163  }
164  free(pv);
165  return nullptr;
166}
167#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
168
169/// GetMainExecutable - Return the path to the main executable, given the
170/// value of argv[0] from program startup.
171std::string getMainExecutable(const char *argv0, void *MainAddr) {
172#if defined(__APPLE__)
173  // On OS X the executable path is saved to the stack by dyld. Reading it
174  // from there is much faster than calling dladdr, especially for large
175  // binaries with symbols.
176  char exe_path[MAXPATHLEN];
177  uint32_t size = sizeof(exe_path);
178  if (_NSGetExecutablePath(exe_path, &size) == 0) {
179    char link_path[MAXPATHLEN];
180    if (realpath(exe_path, link_path))
181      return link_path;
182  }
183#elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
184      defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
185      defined(__FreeBSD_kernel__) || defined(_AIX)
186  char exe_path[PATH_MAX];
187
188  if (getprogpath(exe_path, argv0) != NULL)
189    return exe_path;
190#elif defined(__linux__) || defined(__CYGWIN__)
191  char exe_path[MAXPATHLEN];
192  StringRef aPath("/proc/self/exe");
193  if (sys::fs::exists(aPath)) {
194      // /proc is not always mounted under Linux (chroot for example).
195      ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
196      if (len >= 0)
197          return std::string(exe_path, len);
198  } else {
199      // Fall back to the classical detection.
200      if (getprogpath(exe_path, argv0))
201        return exe_path;
202  }
203#elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
204  // Use dladdr to get executable path if available.
205  Dl_info DLInfo;
206  int err = dladdr(MainAddr, &DLInfo);
207  if (err == 0)
208    return "";
209
210  // If the filename is a symlink, we need to resolve and return the location of
211  // the actual executable.
212  char link_path[MAXPATHLEN];
213  if (realpath(DLInfo.dli_fname, link_path))
214    return link_path;
215#else
216#error GetMainExecutable is not implemented on this host yet.
217#endif
218  return "";
219}
220
221TimePoint<> file_status::getLastAccessedTime() const {
222  return toTimePoint(fs_st_atime);
223}
224
225TimePoint<> file_status::getLastModificationTime() const {
226  return toTimePoint(fs_st_mtime);
227}
228
229UniqueID file_status::getUniqueID() const {
230  return UniqueID(fs_st_dev, fs_st_ino);
231}
232
233uint32_t file_status::getLinkCount() const {
234  return fs_st_nlinks;
235}
236
237ErrorOr<space_info> disk_space(const Twine &Path) {
238  struct STATVFS Vfs;
239  if (::STATVFS(Path.str().c_str(), &Vfs))
240    return std::error_code(errno, std::generic_category());
241  auto FrSize = STATVFS_F_FRSIZE(Vfs);
242  space_info SpaceInfo;
243  SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
244  SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
245  SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
246  return SpaceInfo;
247}
248
249std::error_code current_path(SmallVectorImpl<char> &result) {
250  result.clear();
251
252  const char *pwd = ::getenv("PWD");
253  llvm::sys::fs::file_status PWDStatus, DotStatus;
254  if (pwd && llvm::sys::path::is_absolute(pwd) &&
255      !llvm::sys::fs::status(pwd, PWDStatus) &&
256      !llvm::sys::fs::status(".", DotStatus) &&
257      PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
258    result.append(pwd, pwd + strlen(pwd));
259    return std::error_code();
260  }
261
262#ifdef MAXPATHLEN
263  result.reserve(MAXPATHLEN);
264#else
265// For GNU Hurd
266  result.reserve(1024);
267#endif
268
269  while (true) {
270    if (::getcwd(result.data(), result.capacity()) == nullptr) {
271      // See if there was a real error.
272      if (errno != ENOMEM)
273        return std::error_code(errno, std::generic_category());
274      // Otherwise there just wasn't enough space.
275      result.reserve(result.capacity() * 2);
276    } else
277      break;
278  }
279
280  result.set_size(strlen(result.data()));
281  return std::error_code();
282}
283
284std::error_code set_current_path(const Twine &path) {
285  SmallString<128> path_storage;
286  StringRef p = path.toNullTerminatedStringRef(path_storage);
287
288  if (::chdir(p.begin()) == -1)
289    return std::error_code(errno, std::generic_category());
290
291  return std::error_code();
292}
293
294std::error_code create_directory(const Twine &path, bool IgnoreExisting,
295                                 perms Perms) {
296  SmallString<128> path_storage;
297  StringRef p = path.toNullTerminatedStringRef(path_storage);
298
299  if (::mkdir(p.begin(), Perms) == -1) {
300    if (errno != EEXIST || !IgnoreExisting)
301      return std::error_code(errno, std::generic_category());
302  }
303
304  return std::error_code();
305}
306
307// Note that we are using symbolic link because hard links are not supported by
308// all filesystems (SMB doesn't).
309std::error_code create_link(const Twine &to, const Twine &from) {
310  // Get arguments.
311  SmallString<128> from_storage;
312  SmallString<128> to_storage;
313  StringRef f = from.toNullTerminatedStringRef(from_storage);
314  StringRef t = to.toNullTerminatedStringRef(to_storage);
315
316  if (::symlink(t.begin(), f.begin()) == -1)
317    return std::error_code(errno, std::generic_category());
318
319  return std::error_code();
320}
321
322std::error_code create_hard_link(const Twine &to, const Twine &from) {
323  // Get arguments.
324  SmallString<128> from_storage;
325  SmallString<128> to_storage;
326  StringRef f = from.toNullTerminatedStringRef(from_storage);
327  StringRef t = to.toNullTerminatedStringRef(to_storage);
328
329  if (::link(t.begin(), f.begin()) == -1)
330    return std::error_code(errno, std::generic_category());
331
332  return std::error_code();
333}
334
335std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
336  SmallString<128> path_storage;
337  StringRef p = path.toNullTerminatedStringRef(path_storage);
338
339  struct stat buf;
340  if (lstat(p.begin(), &buf) != 0) {
341    if (errno != ENOENT || !IgnoreNonExisting)
342      return std::error_code(errno, std::generic_category());
343    return std::error_code();
344  }
345
346  // Note: this check catches strange situations. In all cases, LLVM should
347  // only be involved in the creation and deletion of regular files.  This
348  // check ensures that what we're trying to erase is a regular file. It
349  // effectively prevents LLVM from erasing things like /dev/null, any block
350  // special file, or other things that aren't "regular" files.
351  if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
352    return make_error_code(errc::operation_not_permitted);
353
354  if (::remove(p.begin()) == -1) {
355    if (errno != ENOENT || !IgnoreNonExisting)
356      return std::error_code(errno, std::generic_category());
357  }
358
359  return std::error_code();
360}
361
362static bool is_local_impl(struct STATVFS &Vfs) {
363#if defined(__linux__)
364#ifndef NFS_SUPER_MAGIC
365#define NFS_SUPER_MAGIC 0x6969
366#endif
367#ifndef SMB_SUPER_MAGIC
368#define SMB_SUPER_MAGIC 0x517B
369#endif
370#ifndef CIFS_MAGIC_NUMBER
371#define CIFS_MAGIC_NUMBER 0xFF534D42
372#endif
373  switch ((uint32_t)Vfs.f_type) {
374  case NFS_SUPER_MAGIC:
375  case SMB_SUPER_MAGIC:
376  case CIFS_MAGIC_NUMBER:
377    return false;
378  default:
379    return true;
380  }
381#elif defined(__CYGWIN__)
382  // Cygwin doesn't expose this information; would need to use Win32 API.
383  return false;
384#else
385  return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
386#endif
387}
388
389std::error_code is_local(const Twine &Path, bool &Result) {
390  struct STATVFS Vfs;
391  if (::STATVFS(Path.str().c_str(), &Vfs))
392    return std::error_code(errno, std::generic_category());
393
394  Result = is_local_impl(Vfs);
395  return std::error_code();
396}
397
398std::error_code is_local(int FD, bool &Result) {
399  struct STATVFS Vfs;
400  if (::FSTATVFS(FD, &Vfs))
401    return std::error_code(errno, std::generic_category());
402
403  Result = is_local_impl(Vfs);
404  return std::error_code();
405}
406
407std::error_code rename(const Twine &from, const Twine &to) {
408  // Get arguments.
409  SmallString<128> from_storage;
410  SmallString<128> to_storage;
411  StringRef f = from.toNullTerminatedStringRef(from_storage);
412  StringRef t = to.toNullTerminatedStringRef(to_storage);
413
414  if (::rename(f.begin(), t.begin()) == -1)
415    return std::error_code(errno, std::generic_category());
416
417  return std::error_code();
418}
419
420std::error_code resize_file(int FD, uint64_t Size) {
421#if defined(HAVE_POSIX_FALLOCATE)
422  // If we have posix_fallocate use it. Unlike ftruncate it always allocates
423  // space, so we get an error if the disk is full.
424  if (int Err = ::posix_fallocate(FD, 0, Size))
425    return std::error_code(Err, std::generic_category());
426#else
427  // Use ftruncate as a fallback. It may or may not allocate space. At least on
428  // OS X with HFS+ it does.
429  if (::ftruncate(FD, Size) == -1)
430    return std::error_code(errno, std::generic_category());
431#endif
432
433  return std::error_code();
434}
435
436static int convertAccessMode(AccessMode Mode) {
437  switch (Mode) {
438  case AccessMode::Exist:
439    return F_OK;
440  case AccessMode::Write:
441    return W_OK;
442  case AccessMode::Execute:
443    return R_OK | X_OK; // scripts also need R_OK.
444  }
445  llvm_unreachable("invalid enum");
446}
447
448std::error_code access(const Twine &Path, AccessMode Mode) {
449  SmallString<128> PathStorage;
450  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
451
452  if (::access(P.begin(), convertAccessMode(Mode)) == -1)
453    return std::error_code(errno, std::generic_category());
454
455  if (Mode == AccessMode::Execute) {
456    // Don't say that directories are executable.
457    struct stat buf;
458    if (0 != stat(P.begin(), &buf))
459      return errc::permission_denied;
460    if (!S_ISREG(buf.st_mode))
461      return errc::permission_denied;
462  }
463
464  return std::error_code();
465}
466
467bool can_execute(const Twine &Path) {
468  return !access(Path, AccessMode::Execute);
469}
470
471bool equivalent(file_status A, file_status B) {
472  assert(status_known(A) && status_known(B));
473  return A.fs_st_dev == B.fs_st_dev &&
474         A.fs_st_ino == B.fs_st_ino;
475}
476
477std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
478  file_status fsA, fsB;
479  if (std::error_code ec = status(A, fsA))
480    return ec;
481  if (std::error_code ec = status(B, fsB))
482    return ec;
483  result = equivalent(fsA, fsB);
484  return std::error_code();
485}
486
487static void expandTildeExpr(SmallVectorImpl<char> &Path) {
488  StringRef PathStr(Path.begin(), Path.size());
489  if (PathStr.empty() || !PathStr.startswith("~"))
490    return;
491
492  PathStr = PathStr.drop_front();
493  StringRef Expr =
494      PathStr.take_until([](char c) { return path::is_separator(c); });
495  StringRef Remainder = PathStr.substr(Expr.size() + 1);
496  SmallString<128> Storage;
497  if (Expr.empty()) {
498    // This is just ~/..., resolve it to the current user's home dir.
499    if (!path::home_directory(Storage)) {
500      // For some reason we couldn't get the home directory.  Just exit.
501      return;
502    }
503
504    // Overwrite the first character and insert the rest.
505    Path[0] = Storage[0];
506    Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
507    return;
508  }
509
510  // This is a string of the form ~username/, look up this user's entry in the
511  // password database.
512  struct passwd *Entry = nullptr;
513  std::string User = Expr.str();
514  Entry = ::getpwnam(User.c_str());
515
516  if (!Entry) {
517    // Unable to look up the entry, just return back the original path.
518    return;
519  }
520
521  Storage = Remainder;
522  Path.clear();
523  Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
524  llvm::sys::path::append(Path, Storage);
525}
526
527static std::error_code fillStatus(int StatRet, const struct stat &Status,
528                             file_status &Result) {
529  if (StatRet != 0) {
530    std::error_code ec(errno, std::generic_category());
531    if (ec == errc::no_such_file_or_directory)
532      Result = file_status(file_type::file_not_found);
533    else
534      Result = file_status(file_type::status_error);
535    return ec;
536  }
537
538  file_type Type = file_type::type_unknown;
539
540  if (S_ISDIR(Status.st_mode))
541    Type = file_type::directory_file;
542  else if (S_ISREG(Status.st_mode))
543    Type = file_type::regular_file;
544  else if (S_ISBLK(Status.st_mode))
545    Type = file_type::block_file;
546  else if (S_ISCHR(Status.st_mode))
547    Type = file_type::character_file;
548  else if (S_ISFIFO(Status.st_mode))
549    Type = file_type::fifo_file;
550  else if (S_ISSOCK(Status.st_mode))
551    Type = file_type::socket_file;
552  else if (S_ISLNK(Status.st_mode))
553    Type = file_type::symlink_file;
554
555  perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
556  Result = file_status(Type, Perms, Status.st_dev, Status.st_nlink,
557                       Status.st_ino, Status.st_atime, Status.st_mtime,
558                       Status.st_uid, Status.st_gid, Status.st_size);
559
560  return std::error_code();
561}
562
563std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
564  SmallString<128> PathStorage;
565  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
566
567  struct stat Status;
568  int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
569  return fillStatus(StatRet, Status, Result);
570}
571
572std::error_code status(int FD, file_status &Result) {
573  struct stat Status;
574  int StatRet = ::fstat(FD, &Status);
575  return fillStatus(StatRet, Status, Result);
576}
577
578std::error_code setPermissions(const Twine &Path, perms Permissions) {
579  SmallString<128> PathStorage;
580  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
581
582  if (::chmod(P.begin(), Permissions))
583    return std::error_code(errno, std::generic_category());
584  return std::error_code();
585}
586
587std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time) {
588#if defined(HAVE_FUTIMENS)
589  timespec Times[2];
590  Times[0] = Times[1] = sys::toTimeSpec(Time);
591  if (::futimens(FD, Times))
592    return std::error_code(errno, std::generic_category());
593  return std::error_code();
594#elif defined(HAVE_FUTIMES)
595  timeval Times[2];
596  Times[0] = Times[1] = sys::toTimeVal(
597      std::chrono::time_point_cast<std::chrono::microseconds>(Time));
598  if (::futimes(FD, Times))
599    return std::error_code(errno, std::generic_category());
600  return std::error_code();
601#else
602#warning Missing futimes() and futimens()
603  return make_error_code(errc::function_not_supported);
604#endif
605}
606
607std::error_code mapped_file_region::init(int FD, uint64_t Offset,
608                                         mapmode Mode) {
609  assert(Size != 0);
610
611  int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
612  int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
613#if defined(__APPLE__)
614  //----------------------------------------------------------------------
615  // Newer versions of MacOSX have a flag that will allow us to read from
616  // binaries whose code signature is invalid without crashing by using
617  // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
618  // is mapped we can avoid crashing and return zeroes to any pages we try
619  // to read if the media becomes unavailable by using the
620  // MAP_RESILIENT_MEDIA flag.  These flags are only usable when mapping
621  // with PROT_READ, so take care not to specify them otherwise.
622  //----------------------------------------------------------------------
623  if (Mode == readonly) {
624#if defined(MAP_RESILIENT_CODESIGN)
625    flags |= MAP_RESILIENT_CODESIGN;
626#endif
627#if defined(MAP_RESILIENT_MEDIA)
628    flags |= MAP_RESILIENT_MEDIA;
629#endif
630  }
631#endif // #if defined (__APPLE__)
632
633  Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
634  if (Mapping == MAP_FAILED)
635    return std::error_code(errno, std::generic_category());
636  return std::error_code();
637}
638
639mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
640                                       uint64_t offset, std::error_code &ec)
641    : Size(length), Mapping() {
642  // Make sure that the requested size fits within SIZE_T.
643  if (length > std::numeric_limits<size_t>::max()) {
644    ec = make_error_code(errc::invalid_argument);
645    return;
646  }
647
648  ec = init(fd, offset, mode);
649  if (ec)
650    Mapping = nullptr;
651}
652
653mapped_file_region::~mapped_file_region() {
654  if (Mapping)
655    ::munmap(Mapping, Size);
656}
657
658uint64_t mapped_file_region::size() const {
659  assert(Mapping && "Mapping failed but used anyway!");
660  return Size;
661}
662
663char *mapped_file_region::data() const {
664  assert(Mapping && "Mapping failed but used anyway!");
665  return reinterpret_cast<char*>(Mapping);
666}
667
668const char *mapped_file_region::const_data() const {
669  assert(Mapping && "Mapping failed but used anyway!");
670  return reinterpret_cast<const char*>(Mapping);
671}
672
673int mapped_file_region::alignment() {
674  return Process::getPageSize();
675}
676
677std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
678                                                     StringRef path,
679                                                     bool follow_symlinks) {
680  SmallString<128> path_null(path);
681  DIR *directory = ::opendir(path_null.c_str());
682  if (!directory)
683    return std::error_code(errno, std::generic_category());
684
685  it.IterationHandle = reinterpret_cast<intptr_t>(directory);
686  // Add something for replace_filename to replace.
687  path::append(path_null, ".");
688  it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
689  return directory_iterator_increment(it);
690}
691
692std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
693  if (it.IterationHandle)
694    ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
695  it.IterationHandle = 0;
696  it.CurrentEntry = directory_entry();
697  return std::error_code();
698}
699
700std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
701  errno = 0;
702  dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
703  if (cur_dir == nullptr && errno != 0) {
704    return std::error_code(errno, std::generic_category());
705  } else if (cur_dir != nullptr) {
706    StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
707    if ((name.size() == 1 && name[0] == '.') ||
708        (name.size() == 2 && name[0] == '.' && name[1] == '.'))
709      return directory_iterator_increment(it);
710    it.CurrentEntry.replace_filename(name);
711  } else
712    return directory_iterator_destruct(it);
713
714  return std::error_code();
715}
716
717#if !defined(F_GETPATH)
718static bool hasProcSelfFD() {
719  // If we have a /proc filesystem mounted, we can quickly establish the
720  // real name of the file with readlink
721  static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
722  return Result;
723}
724#endif
725
726std::error_code openFileForRead(const Twine &Name, int &ResultFD,
727                                SmallVectorImpl<char> *RealPath) {
728  SmallString<128> Storage;
729  StringRef P = Name.toNullTerminatedStringRef(Storage);
730  int OpenFlags = O_RDONLY;
731#ifdef O_CLOEXEC
732  OpenFlags |= O_CLOEXEC;
733#endif
734  while ((ResultFD = open(P.begin(), OpenFlags)) < 0) {
735    if (errno != EINTR)
736      return std::error_code(errno, std::generic_category());
737  }
738#ifndef O_CLOEXEC
739  int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
740  (void)r;
741  assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
742#endif
743  // Attempt to get the real name of the file, if the user asked
744  if(!RealPath)
745    return std::error_code();
746  RealPath->clear();
747#if defined(F_GETPATH)
748  // When F_GETPATH is availble, it is the quickest way to get
749  // the real path name.
750  char Buffer[MAXPATHLEN];
751  if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
752    RealPath->append(Buffer, Buffer + strlen(Buffer));
753#else
754  char Buffer[PATH_MAX];
755  if (hasProcSelfFD()) {
756    char ProcPath[64];
757    snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
758    ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
759    if (CharCount > 0)
760      RealPath->append(Buffer, Buffer + CharCount);
761  } else {
762    // Use ::realpath to get the real path name
763    if (::realpath(P.begin(), Buffer) != nullptr)
764      RealPath->append(Buffer, Buffer + strlen(Buffer));
765  }
766#endif
767  return std::error_code();
768}
769
770std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
771                            sys::fs::OpenFlags Flags, unsigned Mode) {
772  // Verify that we don't have both "append" and "excl".
773  assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
774         "Cannot specify both 'excl' and 'append' file creation flags!");
775
776  int OpenFlags = O_CREAT;
777
778#ifdef O_CLOEXEC
779  OpenFlags |= O_CLOEXEC;
780#endif
781
782  if (Flags & F_RW)
783    OpenFlags |= O_RDWR;
784  else
785    OpenFlags |= O_WRONLY;
786
787  if (Flags & F_Append)
788    OpenFlags |= O_APPEND;
789  else
790    OpenFlags |= O_TRUNC;
791
792  if (Flags & F_Excl)
793    OpenFlags |= O_EXCL;
794
795  SmallString<128> Storage;
796  StringRef P = Name.toNullTerminatedStringRef(Storage);
797  while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
798    if (errno != EINTR)
799      return std::error_code(errno, std::generic_category());
800  }
801#ifndef O_CLOEXEC
802  int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
803  (void)r;
804  assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
805#endif
806  return std::error_code();
807}
808
809std::error_code getPathFromOpenFD(int FD, SmallVectorImpl<char> &ResultPath) {
810  if (FD < 0)
811    return make_error_code(errc::bad_file_descriptor);
812
813#if defined(F_GETPATH)
814  // When F_GETPATH is availble, it is the quickest way to get
815  // the path from a file descriptor.
816  ResultPath.reserve(MAXPATHLEN);
817  if (::fcntl(FD, F_GETPATH, ResultPath.begin()) == -1)
818    return std::error_code(errno, std::generic_category());
819
820  ResultPath.set_size(strlen(ResultPath.begin()));
821#else
822  // If we have a /proc filesystem mounted, we can quickly establish the
823  // real name of the file with readlink. Otherwise, we don't know how to
824  // get the filename from a file descriptor. Give up.
825  if (!fs::hasProcSelfFD())
826    return make_error_code(errc::function_not_supported);
827
828  ResultPath.reserve(PATH_MAX);
829  char ProcPath[64];
830  snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", FD);
831  ssize_t CharCount = ::readlink(ProcPath, ResultPath.begin(), ResultPath.capacity());
832  if (CharCount < 0)
833      return std::error_code(errno, std::generic_category());
834
835  // Was the filename truncated?
836  if (static_cast<size_t>(CharCount) == ResultPath.capacity()) {
837    // Use lstat to get the size of the filename
838    struct stat sb;
839    if (::lstat(ProcPath, &sb) < 0)
840      return std::error_code(errno, std::generic_category());
841
842    ResultPath.reserve(sb.st_size + 1);
843    CharCount = ::readlink(ProcPath, ResultPath.begin(), ResultPath.capacity());
844    if (CharCount < 0)
845      return std::error_code(errno, std::generic_category());
846
847    // Test for race condition: did the link size change?
848    if (CharCount > sb.st_size)
849      return std::error_code(ENAMETOOLONG, std::generic_category());
850  }
851  ResultPath.set_size(static_cast<size_t>(CharCount));
852#endif
853  return std::error_code();
854}
855
856template <typename T>
857static std::error_code remove_directories_impl(const T &Entry,
858                                               bool IgnoreErrors) {
859  std::error_code EC;
860  directory_iterator Begin(Entry, EC, false);
861  directory_iterator End;
862  while (Begin != End) {
863    auto &Item = *Begin;
864    file_status st;
865    EC = Item.status(st);
866    if (EC && !IgnoreErrors)
867      return EC;
868
869    if (is_directory(st)) {
870      EC = remove_directories_impl(Item, IgnoreErrors);
871      if (EC && !IgnoreErrors)
872        return EC;
873    }
874
875    EC = fs::remove(Item.path(), true);
876    if (EC && !IgnoreErrors)
877      return EC;
878
879    Begin.increment(EC);
880    if (EC && !IgnoreErrors)
881      return EC;
882  }
883  return std::error_code();
884}
885
886std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
887  auto EC = remove_directories_impl(path, IgnoreErrors);
888  if (EC && !IgnoreErrors)
889    return EC;
890  EC = fs::remove(path, true);
891  if (EC && !IgnoreErrors)
892    return EC;
893  return std::error_code();
894}
895
896std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
897                          bool expand_tilde) {
898  dest.clear();
899  if (path.isTriviallyEmpty())
900    return std::error_code();
901
902  if (expand_tilde) {
903    SmallString<128> Storage;
904    path.toVector(Storage);
905    expandTildeExpr(Storage);
906    return real_path(Storage, dest, false);
907  }
908
909  int fd;
910  std::error_code EC = openFileForRead(path, fd, &dest);
911
912  if (EC)
913    return EC;
914  ::close(fd);
915  return std::error_code();
916}
917
918} // end namespace fs
919
920namespace path {
921
922bool home_directory(SmallVectorImpl<char> &result) {
923  char *RequestedDir = getenv("HOME");
924  if (!RequestedDir) {
925    struct passwd *pw = getpwuid(getuid());
926    if (pw && pw->pw_dir)
927      RequestedDir = pw->pw_dir;
928  }
929  if (!RequestedDir)
930    return false;
931
932  result.clear();
933  result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
934  return true;
935}
936
937static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
938  #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
939  // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
940  // macros defined in <unistd.h> on darwin >= 9
941  int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
942                         : _CS_DARWIN_USER_CACHE_DIR;
943  size_t ConfLen = confstr(ConfName, nullptr, 0);
944  if (ConfLen > 0) {
945    do {
946      Result.resize(ConfLen);
947      ConfLen = confstr(ConfName, Result.data(), Result.size());
948    } while (ConfLen > 0 && ConfLen != Result.size());
949
950    if (ConfLen > 0) {
951      assert(Result.back() == 0);
952      Result.pop_back();
953      return true;
954    }
955
956    Result.clear();
957  }
958  #endif
959  return false;
960}
961
962static bool getUserCacheDir(SmallVectorImpl<char> &Result) {
963  // First try using XDG_CACHE_HOME env variable,
964  // as specified in XDG Base Directory Specification at
965  // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
966  if (const char *XdgCacheDir = std::getenv("XDG_CACHE_HOME")) {
967    Result.clear();
968    Result.append(XdgCacheDir, XdgCacheDir + strlen(XdgCacheDir));
969    return true;
970  }
971
972  // Try Darwin configuration query
973  if (getDarwinConfDir(false, Result))
974    return true;
975
976  // Use "$HOME/.cache" if $HOME is available
977  if (home_directory(Result)) {
978    append(Result, ".cache");
979    return true;
980  }
981
982  return false;
983}
984
985static const char *getEnvTempDir() {
986  // Check whether the temporary directory is specified by an environment
987  // variable.
988  const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
989  for (const char *Env : EnvironmentVariables) {
990    if (const char *Dir = std::getenv(Env))
991      return Dir;
992  }
993
994  return nullptr;
995}
996
997static const char *getDefaultTempDir(bool ErasedOnReboot) {
998#ifdef P_tmpdir
999  if ((bool)P_tmpdir)
1000    return P_tmpdir;
1001#endif
1002
1003  if (ErasedOnReboot)
1004    return "/tmp";
1005  return "/var/tmp";
1006}
1007
1008void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1009  Result.clear();
1010
1011  if (ErasedOnReboot) {
1012    // There is no env variable for the cache directory.
1013    if (const char *RequestedDir = getEnvTempDir()) {
1014      Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1015      return;
1016    }
1017  }
1018
1019  if (getDarwinConfDir(ErasedOnReboot, Result))
1020    return;
1021
1022  const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1023  Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1024}
1025
1026} // end namespace path
1027
1028} // end namespace sys
1029} // end namespace llvm
1030