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:
375 #elif defined(__CYGWIN__)
376 // Cygwin doesn't expose this information; would need to use Win32 API.
379 return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
383 std::error_code is_local(const Twine &Path, bool &Result) {
385 if (::STATVFS(Path.str().c_str(), &Vfs))
386 return std::error_code(errno, std::generic_category());
388 Result = is_local_impl(Vfs);
389 return std::error_code();
392 std::error_code is_local(int FD, bool &Result) {
394 if (::FSTATVFS(FD, &Vfs))
395 return std::error_code(errno, std::generic_category());
397 Result = is_local_impl(Vfs);
398 return std::error_code();
401 std::error_code rename(const Twine &from, const Twine &to) {
403 SmallString<128> from_storage;
404 SmallString<128> to_storage;
405 StringRef f = from.toNullTerminatedStringRef(from_storage);
406 StringRef t = to.toNullTerminatedStringRef(to_storage);
408 if (::rename(f.begin(), t.begin()) == -1)
409 return std::error_code(errno, std::generic_category());
411 return std::error_code();
414 std::error_code resize_file(int FD, uint64_t Size) {
415 #if defined(HAVE_POSIX_FALLOCATE)
416 // If we have posix_fallocate use it. Unlike ftruncate it always allocates
417 // space, so we get an error if the disk is full.
418 if (int Err = ::posix_fallocate(FD, 0, Size))
419 return std::error_code(Err, std::generic_category());
421 // Use ftruncate as a fallback. It may or may not allocate space. At least on
422 // OS X with HFS+ it does.
423 if (::ftruncate(FD, Size) == -1)
424 return std::error_code(errno, std::generic_category());
427 return std::error_code();
430 static int convertAccessMode(AccessMode Mode) {
432 case AccessMode::Exist:
434 case AccessMode::Write:
436 case AccessMode::Execute:
437 return R_OK | X_OK; // scripts also need R_OK.
439 llvm_unreachable("invalid enum");
442 std::error_code access(const Twine &Path, AccessMode Mode) {
443 SmallString<128> PathStorage;
444 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
446 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
447 return std::error_code(errno, std::generic_category());
449 if (Mode == AccessMode::Execute) {
450 // Don't say that directories are executable.
452 if (0 != stat(P.begin(), &buf))
453 return errc::permission_denied;
454 if (!S_ISREG(buf.st_mode))
455 return errc::permission_denied;
458 return std::error_code();
461 bool can_execute(const Twine &Path) {
462 return !access(Path, AccessMode::Execute);
465 bool equivalent(file_status A, file_status B) {
466 assert(status_known(A) && status_known(B));
467 return A.fs_st_dev == B.fs_st_dev &&
468 A.fs_st_ino == B.fs_st_ino;
471 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
472 file_status fsA, fsB;
473 if (std::error_code ec = status(A, fsA))
475 if (std::error_code ec = status(B, fsB))
477 result = equivalent(fsA, fsB);
478 return std::error_code();
481 static std::error_code fillStatus(int StatRet, const struct stat &Status,
482 file_status &Result) {
484 std::error_code ec(errno, std::generic_category());
485 if (ec == errc::no_such_file_or_directory)
486 Result = file_status(file_type::file_not_found);
488 Result = file_status(file_type::status_error);
492 file_type Type = file_type::type_unknown;
494 if (S_ISDIR(Status.st_mode))
495 Type = file_type::directory_file;
496 else if (S_ISREG(Status.st_mode))
497 Type = file_type::regular_file;
498 else if (S_ISBLK(Status.st_mode))
499 Type = file_type::block_file;
500 else if (S_ISCHR(Status.st_mode))
501 Type = file_type::character_file;
502 else if (S_ISFIFO(Status.st_mode))
503 Type = file_type::fifo_file;
504 else if (S_ISSOCK(Status.st_mode))
505 Type = file_type::socket_file;
506 else if (S_ISLNK(Status.st_mode))
507 Type = file_type::symlink_file;
509 perms Perms = static_cast<perms>(Status.st_mode);
511 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_atime,
512 Status.st_mtime, Status.st_uid, Status.st_gid,
515 return std::error_code();
518 std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
519 SmallString<128> PathStorage;
520 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
523 int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
524 return fillStatus(StatRet, Status, Result);
527 std::error_code status(int FD, file_status &Result) {
529 int StatRet = ::fstat(FD, &Status);
530 return fillStatus(StatRet, Status, Result);
533 std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time) {
534 #if defined(HAVE_FUTIMENS)
536 Times[0] = Times[1] = sys::toTimeSpec(Time);
537 if (::futimens(FD, Times))
538 return std::error_code(errno, std::generic_category());
539 return std::error_code();
540 #elif defined(HAVE_FUTIMES)
542 Times[0] = Times[1] = sys::toTimeVal(
543 std::chrono::time_point_cast<std::chrono::microseconds>(Time));
544 if (::futimes(FD, Times))
545 return std::error_code(errno, std::generic_category());
546 return std::error_code();
548 #warning Missing futimes() and futimens()
549 return make_error_code(errc::function_not_supported);
553 std::error_code mapped_file_region::init(int FD, uint64_t Offset,
557 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
558 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
559 #if defined(__APPLE__)
560 //----------------------------------------------------------------------
561 // Newer versions of MacOSX have a flag that will allow us to read from
562 // binaries whose code signature is invalid without crashing by using
563 // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
564 // is mapped we can avoid crashing and return zeroes to any pages we try
565 // to read if the media becomes unavailable by using the
566 // MAP_RESILIENT_MEDIA flag. These flags are only usable when mapping
567 // with PROT_READ, so take care not to specify them otherwise.
568 //----------------------------------------------------------------------
569 if (Mode == readonly) {
570 #if defined(MAP_RESILIENT_CODESIGN)
571 flags |= MAP_RESILIENT_CODESIGN;
573 #if defined(MAP_RESILIENT_MEDIA)
574 flags |= MAP_RESILIENT_MEDIA;
577 #endif // #if defined (__APPLE__)
579 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
580 if (Mapping == MAP_FAILED)
581 return std::error_code(errno, std::generic_category());
582 return std::error_code();
585 mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
586 uint64_t offset, std::error_code &ec)
587 : Size(length), Mapping() {
588 // Make sure that the requested size fits within SIZE_T.
589 if (length > std::numeric_limits<size_t>::max()) {
590 ec = make_error_code(errc::invalid_argument);
594 ec = init(fd, offset, mode);
599 mapped_file_region::~mapped_file_region() {
601 ::munmap(Mapping, Size);
604 uint64_t mapped_file_region::size() const {
605 assert(Mapping && "Mapping failed but used anyway!");
609 char *mapped_file_region::data() const {
610 assert(Mapping && "Mapping failed but used anyway!");
611 return reinterpret_cast<char*>(Mapping);
614 const char *mapped_file_region::const_data() const {
615 assert(Mapping && "Mapping failed but used anyway!");
616 return reinterpret_cast<const char*>(Mapping);
619 int mapped_file_region::alignment() {
620 return Process::getPageSize();
623 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
625 bool follow_symlinks) {
626 SmallString<128> path_null(path);
627 DIR *directory = ::opendir(path_null.c_str());
629 return std::error_code(errno, std::generic_category());
631 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
632 // Add something for replace_filename to replace.
633 path::append(path_null, ".");
634 it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
635 return directory_iterator_increment(it);
638 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
639 if (it.IterationHandle)
640 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
641 it.IterationHandle = 0;
642 it.CurrentEntry = directory_entry();
643 return std::error_code();
646 std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
648 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
649 if (cur_dir == nullptr && errno != 0) {
650 return std::error_code(errno, std::generic_category());
651 } else if (cur_dir != nullptr) {
652 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
653 if ((name.size() == 1 && name[0] == '.') ||
654 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
655 return directory_iterator_increment(it);
656 it.CurrentEntry.replace_filename(name);
658 return directory_iterator_destruct(it);
660 return std::error_code();
663 #if !defined(F_GETPATH)
664 static bool hasProcSelfFD() {
665 // If we have a /proc filesystem mounted, we can quickly establish the
666 // real name of the file with readlink
667 static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
672 std::error_code openFileForRead(const Twine &Name, int &ResultFD,
673 SmallVectorImpl<char> *RealPath) {
674 SmallString<128> Storage;
675 StringRef P = Name.toNullTerminatedStringRef(Storage);
676 int OpenFlags = O_RDONLY;
678 OpenFlags |= O_CLOEXEC;
680 while ((ResultFD = open(P.begin(), OpenFlags)) < 0) {
682 return std::error_code(errno, std::generic_category());
685 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
687 assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
689 // Attempt to get the real name of the file, if the user asked
691 return std::error_code();
693 #if defined(F_GETPATH)
694 // When F_GETPATH is availble, it is the quickest way to get
695 // the real path name.
696 char Buffer[MAXPATHLEN];
697 if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
698 RealPath->append(Buffer, Buffer + strlen(Buffer));
700 char Buffer[PATH_MAX];
701 if (hasProcSelfFD()) {
703 snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
704 ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
706 RealPath->append(Buffer, Buffer + CharCount);
708 // Use ::realpath to get the real path name
709 if (::realpath(P.begin(), Buffer) != nullptr)
710 RealPath->append(Buffer, Buffer + strlen(Buffer));
713 return std::error_code();
716 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
717 sys::fs::OpenFlags Flags, unsigned Mode) {
718 // Verify that we don't have both "append" and "excl".
719 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
720 "Cannot specify both 'excl' and 'append' file creation flags!");
722 int OpenFlags = O_CREAT;
725 OpenFlags |= O_CLOEXEC;
731 OpenFlags |= O_WRONLY;
733 if (Flags & F_Append)
734 OpenFlags |= O_APPEND;
736 OpenFlags |= O_TRUNC;
741 SmallString<128> Storage;
742 StringRef P = Name.toNullTerminatedStringRef(Storage);
743 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
745 return std::error_code(errno, std::generic_category());
748 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
750 assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
752 return std::error_code();
755 std::error_code getPathFromOpenFD(int FD, SmallVectorImpl<char> &ResultPath) {
757 return make_error_code(errc::bad_file_descriptor);
759 #if defined(F_GETPATH)
760 // When F_GETPATH is availble, it is the quickest way to get
761 // the path from a file descriptor.
762 ResultPath.reserve(MAXPATHLEN);
763 if (::fcntl(FD, F_GETPATH, ResultPath.begin()) == -1)
764 return std::error_code(errno, std::generic_category());
766 ResultPath.set_size(strlen(ResultPath.begin()));
768 // If we have a /proc filesystem mounted, we can quickly establish the
769 // real name of the file with readlink. Otherwise, we don't know how to
770 // get the filename from a file descriptor. Give up.
771 if (!fs::hasProcSelfFD())
772 return make_error_code(errc::function_not_supported);
774 ResultPath.reserve(PATH_MAX);
776 snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", FD);
777 ssize_t CharCount = ::readlink(ProcPath, ResultPath.begin(), ResultPath.capacity());
779 return std::error_code(errno, std::generic_category());
781 // Was the filename truncated?
782 if (static_cast<size_t>(CharCount) == ResultPath.capacity()) {
783 // Use lstat to get the size of the filename
785 if (::lstat(ProcPath, &sb) < 0)
786 return std::error_code(errno, std::generic_category());
788 ResultPath.reserve(sb.st_size + 1);
789 CharCount = ::readlink(ProcPath, ResultPath.begin(), ResultPath.capacity());
791 return std::error_code(errno, std::generic_category());
793 // Test for race condition: did the link size change?
794 if (CharCount > sb.st_size)
795 return std::error_code(ENAMETOOLONG, std::generic_category());
797 ResultPath.set_size(static_cast<size_t>(CharCount));
799 return std::error_code();
802 template <typename T>
803 static std::error_code remove_directories_impl(const T &Entry,
806 directory_iterator Begin(Entry, EC, false);
807 directory_iterator End;
808 while (Begin != End) {
811 EC = Item.status(st);
812 if (EC && !IgnoreErrors)
815 if (is_directory(st)) {
816 EC = remove_directories_impl(Item, IgnoreErrors);
817 if (EC && !IgnoreErrors)
821 EC = fs::remove(Item.path(), true);
822 if (EC && !IgnoreErrors)
826 if (EC && !IgnoreErrors)
829 return std::error_code();
832 std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
833 auto EC = remove_directories_impl(path, IgnoreErrors);
834 if (EC && !IgnoreErrors)
836 EC = fs::remove(path, true);
837 if (EC && !IgnoreErrors)
839 return std::error_code();
842 } // end namespace fs
846 bool home_directory(SmallVectorImpl<char> &result) {
847 if (char *RequestedDir = getenv("HOME")) {
849 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
856 static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
857 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
858 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
859 // macros defined in <unistd.h> on darwin >= 9
860 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
861 : _CS_DARWIN_USER_CACHE_DIR;
862 size_t ConfLen = confstr(ConfName, nullptr, 0);
865 Result.resize(ConfLen);
866 ConfLen = confstr(ConfName, Result.data(), Result.size());
867 } while (ConfLen > 0 && ConfLen != Result.size());
870 assert(Result.back() == 0);
881 static bool getUserCacheDir(SmallVectorImpl<char> &Result) {
882 // First try using XDG_CACHE_HOME env variable,
883 // as specified in XDG Base Directory Specification at
884 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
885 if (const char *XdgCacheDir = std::getenv("XDG_CACHE_HOME")) {
887 Result.append(XdgCacheDir, XdgCacheDir + strlen(XdgCacheDir));
891 // Try Darwin configuration query
892 if (getDarwinConfDir(false, Result))
895 // Use "$HOME/.cache" if $HOME is available
896 if (home_directory(Result)) {
897 append(Result, ".cache");
904 static const char *getEnvTempDir() {
905 // Check whether the temporary directory is specified by an environment
907 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
908 for (const char *Env : EnvironmentVariables) {
909 if (const char *Dir = std::getenv(Env))
916 static const char *getDefaultTempDir(bool ErasedOnReboot) {
927 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
930 if (ErasedOnReboot) {
931 // There is no env variable for the cache directory.
932 if (const char *RequestedDir = getEnvTempDir()) {
933 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
938 if (getDarwinConfDir(ErasedOnReboot, Result))
941 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
942 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
945 } // end namespace path
947 } // end namespace sys
948 } // end namespace llvm