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