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