1 //===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Unix specific implementation of the Path API.
12 //===----------------------------------------------------------------------===//
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic UNIX code that
16 //=== is guaranteed to work on *all* UNIX variants.
17 //===----------------------------------------------------------------------===//
31 #ifdef HAVE_SYS_MMAN_H
36 # define NAMLEN(dirent) strlen((dirent)->d_name)
38 # define dirent direct
39 # define NAMLEN(dirent) (dirent)->d_namlen
41 # include <sys/ndir.h>
52 #include <mach-o/dyld.h>
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
63 #if defined(__GNU__) && !defined(PATH_MAX)
64 # define PATH_MAX 4096
67 #include <sys/types.h>
68 #if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && \
70 #include <sys/statvfs.h>
71 #define STATVFS statvfs
72 #define FSTATVFS fstatvfs
73 #define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
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>
82 #if defined(HAVE_LINUX_NFS_FS_H)
83 #include <linux/nfs_fs.h>
85 #if defined(HAVE_LINUX_SMB_H)
86 #include <linux/smb.h>
91 #include <sys/mount.h>
93 #define STATVFS statfs
94 #define FSTATVFS fstatfs
95 #define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
98 #if defined(__NetBSD__)
99 #define STATVFS_F_FLAG(vfs) (vfs).f_flag
101 #define STATVFS_F_FLAG(vfs) (vfs).f_flags
104 using namespace llvm;
109 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
110 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
111 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__) || \
114 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
117 char fullpath[PATH_MAX];
119 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
120 if (!realpath(fullpath, ret))
122 if (stat(fullpath, &sb) != 0)
129 getprogpath(char ret[PATH_MAX], const char *bin)
133 /* First approach: absolute path. */
135 if (test_dir(ret, "/", bin) == 0)
140 /* Second approach: relative path. */
141 if (strchr(bin, '/')) {
143 if (!getcwd(cwd, PATH_MAX))
145 if (test_dir(ret, cwd, bin) == 0)
150 /* Third approach: $PATH */
151 if ((pv = getenv("PATH")) == nullptr)
156 while ((t = strsep(&s, ":")) != nullptr) {
157 if (test_dir(ret, t, bin) == 0) {
165 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
167 /// GetMainExecutable - Return the path to the main executable, given the
168 /// value of argv[0] from program startup.
169 std::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))
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];
186 if (getprogpath(exe_path, argv0) != NULL)
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));
195 return std::string(exe_path, len);
197 // Fall back to the classical detection.
198 if (getprogpath(exe_path, argv0))
201 #elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
202 // Use dladdr to get executable path if available.
204 int err = dladdr(MainAddr, &DLInfo);
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))
214 #error GetMainExecutable is not implemented on this host yet.
219 TimePoint<> file_status::getLastAccessedTime() const {
220 return toTimePoint(fs_st_atime);
223 TimePoint<> file_status::getLastModificationTime() const {
224 return toTimePoint(fs_st_mtime);
227 UniqueID file_status::getUniqueID() const {
228 return UniqueID(fs_st_dev, fs_st_ino);
231 ErrorOr<space_info> disk_space(const Twine &Path) {
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;
243 std::error_code current_path(SmallVectorImpl<char> &result) {
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();
257 result.reserve(MAXPATHLEN);
260 result.reserve(1024);
264 if (::getcwd(result.data(), result.capacity()) == nullptr) {
265 // See if there was a real error.
267 return std::error_code(errno, std::generic_category());
268 // Otherwise there just wasn't enough space.
269 result.reserve(result.capacity() * 2);
274 result.set_size(strlen(result.data()));
275 return std::error_code();
278 std::error_code set_current_path(const Twine &path) {
279 SmallString<128> path_storage;
280 StringRef p = path.toNullTerminatedStringRef(path_storage);
282 if (::chdir(p.begin()) == -1)
283 return std::error_code(errno, std::generic_category());
285 return std::error_code();
288 std::error_code create_directory(const Twine &path, bool IgnoreExisting,
290 SmallString<128> path_storage;
291 StringRef p = path.toNullTerminatedStringRef(path_storage);
293 if (::mkdir(p.begin(), Perms) == -1) {
294 if (errno != EEXIST || !IgnoreExisting)
295 return std::error_code(errno, std::generic_category());
298 return std::error_code();
301 // Note that we are using symbolic link because hard links are not supported by
302 // all filesystems (SMB doesn't).
303 std::error_code create_link(const Twine &to, const Twine &from) {
305 SmallString<128> from_storage;
306 SmallString<128> to_storage;
307 StringRef f = from.toNullTerminatedStringRef(from_storage);
308 StringRef t = to.toNullTerminatedStringRef(to_storage);
310 if (::symlink(t.begin(), f.begin()) == -1)
311 return std::error_code(errno, std::generic_category());
313 return std::error_code();
316 std::error_code create_hard_link(const Twine &to, const Twine &from) {
318 SmallString<128> from_storage;
319 SmallString<128> to_storage;
320 StringRef f = from.toNullTerminatedStringRef(from_storage);
321 StringRef t = to.toNullTerminatedStringRef(to_storage);
323 if (::link(t.begin(), f.begin()) == -1)
324 return std::error_code(errno, std::generic_category());
326 return std::error_code();
329 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
330 SmallString<128> path_storage;
331 StringRef p = path.toNullTerminatedStringRef(path_storage);
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();
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);
348 if (::remove(p.begin()) == -1) {
349 if (errno != ENOENT || !IgnoreNonExisting)
350 return std::error_code(errno, std::generic_category());
353 return std::error_code();
356 static bool is_local_impl(struct STATVFS &Vfs) {
357 #if defined(__linux__)
358 #ifndef NFS_SUPER_MAGIC
359 #define NFS_SUPER_MAGIC 0x6969
361 #ifndef SMB_SUPER_MAGIC
362 #define SMB_SUPER_MAGIC 0x517B
364 #ifndef CIFS_MAGIC_NUMBER
365 #define CIFS_MAGIC_NUMBER 0xFF534D42
367 switch ((uint32_t)Vfs.f_type) {
368 case NFS_SUPER_MAGIC:
369 case SMB_SUPER_MAGIC:
370 case CIFS_MAGIC_NUMBER:
376 return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
380 std::error_code is_local(const Twine &Path, bool &Result) {
382 if (::STATVFS(Path.str().c_str(), &Vfs))
383 return std::error_code(errno, std::generic_category());
385 Result = is_local_impl(Vfs);
386 return std::error_code();
389 std::error_code is_local(int FD, bool &Result) {
391 if (::FSTATVFS(FD, &Vfs))
392 return std::error_code(errno, std::generic_category());
394 Result = is_local_impl(Vfs);
395 return std::error_code();
398 std::error_code rename(const Twine &from, const Twine &to) {
400 SmallString<128> from_storage;
401 SmallString<128> to_storage;
402 StringRef f = from.toNullTerminatedStringRef(from_storage);
403 StringRef t = to.toNullTerminatedStringRef(to_storage);
405 if (::rename(f.begin(), t.begin()) == -1)
406 return std::error_code(errno, std::generic_category());
408 return std::error_code();
411 std::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());
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());
424 return std::error_code();
427 static int convertAccessMode(AccessMode Mode) {
429 case AccessMode::Exist:
431 case AccessMode::Write:
433 case AccessMode::Execute:
434 return R_OK | X_OK; // scripts also need R_OK.
436 llvm_unreachable("invalid enum");
439 std::error_code access(const Twine &Path, AccessMode Mode) {
440 SmallString<128> PathStorage;
441 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
443 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
444 return std::error_code(errno, std::generic_category());
446 if (Mode == AccessMode::Execute) {
447 // Don't say that directories are executable.
449 if (0 != stat(P.begin(), &buf))
450 return errc::permission_denied;
451 if (!S_ISREG(buf.st_mode))
452 return errc::permission_denied;
455 return std::error_code();
458 bool can_execute(const Twine &Path) {
459 return !access(Path, AccessMode::Execute);
462 bool 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;
468 std::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))
472 if (std::error_code ec = status(B, fsB))
474 result = equivalent(fsA, fsB);
475 return std::error_code();
478 static std::error_code fillStatus(int StatRet, const struct stat &Status,
479 file_status &Result) {
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);
485 Result = file_status(file_type::status_error);
489 file_type Type = file_type::type_unknown;
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;
504 perms Perms = static_cast<perms>(Status.st_mode);
506 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_atime,
507 Status.st_mtime, Status.st_uid, Status.st_gid,
510 return std::error_code();
513 std::error_code status(const Twine &Path, file_status &Result) {
514 SmallString<128> PathStorage;
515 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
518 int StatRet = ::stat(P.begin(), &Status);
519 return fillStatus(StatRet, Status, Result);
522 std::error_code status(int FD, file_status &Result) {
524 int StatRet = ::fstat(FD, &Status);
525 return fillStatus(StatRet, Status, Result);
528 std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time) {
529 #if defined(HAVE_FUTIMENS)
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)
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();
543 #warning Missing futimes() and futimens()
544 return make_error_code(errc::function_not_supported);
548 std::error_code mapped_file_region::init(int FD, uint64_t Offset,
552 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
553 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
555 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
556 if (Mapping == MAP_FAILED)
557 return std::error_code(errno, std::generic_category());
558 return std::error_code();
561 mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
562 uint64_t offset, std::error_code &ec)
563 : Size(length), Mapping() {
564 // Make sure that the requested size fits within SIZE_T.
565 if (length > std::numeric_limits<size_t>::max()) {
566 ec = make_error_code(errc::invalid_argument);
570 ec = init(fd, offset, mode);
575 mapped_file_region::~mapped_file_region() {
577 ::munmap(Mapping, Size);
580 uint64_t mapped_file_region::size() const {
581 assert(Mapping && "Mapping failed but used anyway!");
585 char *mapped_file_region::data() const {
586 assert(Mapping && "Mapping failed but used anyway!");
587 return reinterpret_cast<char*>(Mapping);
590 const char *mapped_file_region::const_data() const {
591 assert(Mapping && "Mapping failed but used anyway!");
592 return reinterpret_cast<const char*>(Mapping);
595 int mapped_file_region::alignment() {
596 return Process::getPageSize();
599 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
601 SmallString<128> path_null(path);
602 DIR *directory = ::opendir(path_null.c_str());
604 return std::error_code(errno, std::generic_category());
606 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
607 // Add something for replace_filename to replace.
608 path::append(path_null, ".");
609 it.CurrentEntry = directory_entry(path_null.str());
610 return directory_iterator_increment(it);
613 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
614 if (it.IterationHandle)
615 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
616 it.IterationHandle = 0;
617 it.CurrentEntry = directory_entry();
618 return std::error_code();
621 std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
623 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
624 if (cur_dir == nullptr && errno != 0) {
625 return std::error_code(errno, std::generic_category());
626 } else if (cur_dir != nullptr) {
627 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
628 if ((name.size() == 1 && name[0] == '.') ||
629 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
630 return directory_iterator_increment(it);
631 it.CurrentEntry.replace_filename(name);
633 return directory_iterator_destruct(it);
635 return std::error_code();
638 #if !defined(F_GETPATH)
639 static bool hasProcSelfFD() {
640 // If we have a /proc filesystem mounted, we can quickly establish the
641 // real name of the file with readlink
642 static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
647 std::error_code openFileForRead(const Twine &Name, int &ResultFD,
648 SmallVectorImpl<char> *RealPath) {
649 SmallString<128> Storage;
650 StringRef P = Name.toNullTerminatedStringRef(Storage);
651 int OpenFlags = O_RDONLY;
653 OpenFlags |= O_CLOEXEC;
655 while ((ResultFD = open(P.begin(), OpenFlags)) < 0) {
657 return std::error_code(errno, std::generic_category());
660 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
662 assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
664 // Attempt to get the real name of the file, if the user asked
666 return std::error_code();
668 #if defined(F_GETPATH)
669 // When F_GETPATH is availble, it is the quickest way to get
670 // the real path name.
671 char Buffer[MAXPATHLEN];
672 if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
673 RealPath->append(Buffer, Buffer + strlen(Buffer));
675 char Buffer[PATH_MAX];
676 if (hasProcSelfFD()) {
678 snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
679 ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
681 RealPath->append(Buffer, Buffer + CharCount);
683 // Use ::realpath to get the real path name
684 if (::realpath(P.begin(), Buffer) != nullptr)
685 RealPath->append(Buffer, Buffer + strlen(Buffer));
688 return std::error_code();
691 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
692 sys::fs::OpenFlags Flags, unsigned Mode) {
693 // Verify that we don't have both "append" and "excl".
694 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
695 "Cannot specify both 'excl' and 'append' file creation flags!");
697 int OpenFlags = O_CREAT;
700 OpenFlags |= O_CLOEXEC;
706 OpenFlags |= O_WRONLY;
708 if (Flags & F_Append)
709 OpenFlags |= O_APPEND;
711 OpenFlags |= O_TRUNC;
716 SmallString<128> Storage;
717 StringRef P = Name.toNullTerminatedStringRef(Storage);
718 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
720 return std::error_code(errno, std::generic_category());
723 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
725 assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
727 return std::error_code();
730 std::error_code getPathFromOpenFD(int FD, SmallVectorImpl<char> &ResultPath) {
732 return make_error_code(errc::bad_file_descriptor);
734 #if defined(F_GETPATH)
735 // When F_GETPATH is availble, it is the quickest way to get
736 // the path from a file descriptor.
737 ResultPath.reserve(MAXPATHLEN);
738 if (::fcntl(FD, F_GETPATH, ResultPath.begin()) == -1)
739 return std::error_code(errno, std::generic_category());
741 ResultPath.set_size(strlen(ResultPath.begin()));
743 // If we have a /proc filesystem mounted, we can quickly establish the
744 // real name of the file with readlink. Otherwise, we don't know how to
745 // get the filename from a file descriptor. Give up.
746 if (!fs::hasProcSelfFD())
747 return make_error_code(errc::function_not_supported);
749 ResultPath.reserve(PATH_MAX);
751 snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", FD);
752 ssize_t CharCount = ::readlink(ProcPath, ResultPath.begin(), ResultPath.capacity());
754 return std::error_code(errno, std::generic_category());
756 // Was the filename truncated?
757 if (static_cast<size_t>(CharCount) == ResultPath.capacity()) {
758 // Use lstat to get the size of the filename
760 if (::lstat(ProcPath, &sb) < 0)
761 return std::error_code(errno, std::generic_category());
763 ResultPath.reserve(sb.st_size + 1);
764 CharCount = ::readlink(ProcPath, ResultPath.begin(), ResultPath.capacity());
766 return std::error_code(errno, std::generic_category());
768 // Test for race condition: did the link size change?
769 if (CharCount > sb.st_size)
770 return std::error_code(ENAMETOOLONG, std::generic_category());
772 ResultPath.set_size(static_cast<size_t>(CharCount));
774 return std::error_code();
777 } // end namespace fs
781 bool home_directory(SmallVectorImpl<char> &result) {
782 if (char *RequestedDir = getenv("HOME")) {
784 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
791 static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
792 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
793 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
794 // macros defined in <unistd.h> on darwin >= 9
795 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
796 : _CS_DARWIN_USER_CACHE_DIR;
797 size_t ConfLen = confstr(ConfName, nullptr, 0);
800 Result.resize(ConfLen);
801 ConfLen = confstr(ConfName, Result.data(), Result.size());
802 } while (ConfLen > 0 && ConfLen != Result.size());
805 assert(Result.back() == 0);
816 static bool getUserCacheDir(SmallVectorImpl<char> &Result) {
817 // First try using XDG_CACHE_HOME env variable,
818 // as specified in XDG Base Directory Specification at
819 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
820 if (const char *XdgCacheDir = std::getenv("XDG_CACHE_HOME")) {
822 Result.append(XdgCacheDir, XdgCacheDir + strlen(XdgCacheDir));
826 // Try Darwin configuration query
827 if (getDarwinConfDir(false, Result))
830 // Use "$HOME/.cache" if $HOME is available
831 if (home_directory(Result)) {
832 append(Result, ".cache");
839 static const char *getEnvTempDir() {
840 // Check whether the temporary directory is specified by an environment
842 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
843 for (const char *Env : EnvironmentVariables) {
844 if (const char *Dir = std::getenv(Env))
851 static const char *getDefaultTempDir(bool ErasedOnReboot) {
862 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
865 if (ErasedOnReboot) {
866 // There is no env variable for the cache directory.
867 if (const char *RequestedDir = getEnvTempDir()) {
868 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
873 if (getDarwinConfDir(ErasedOnReboot, Result))
876 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
877 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
880 } // end namespace path
882 } // end namespace sys
883 } // end namespace llvm