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>
54 #include <mach-o/dyld.h>
58 // Both stdio.h and cstdio are included via different paths and
59 // stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
65 #if defined(__GNU__) && !defined(PATH_MAX)
66 # define PATH_MAX 4096
69 #include <sys/types.h>
70 #if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && \
72 #include <sys/statvfs.h>
73 #define STATVFS statvfs
74 #define FSTATVFS fstatvfs
75 #define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
77 #if defined(__OpenBSD__) || defined(__FreeBSD__)
78 #include <sys/param.h>
79 #include <sys/mount.h>
80 #elif defined(__linux__)
81 #if defined(HAVE_LINUX_MAGIC_H)
82 #include <linux/magic.h>
84 #if defined(HAVE_LINUX_NFS_FS_H)
85 #include <linux/nfs_fs.h>
87 #if defined(HAVE_LINUX_SMB_H)
88 #include <linux/smb.h>
93 #include <sys/mount.h>
95 #define STATVFS statfs
96 #define FSTATVFS fstatfs
97 #define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
100 #if defined(__NetBSD__)
101 #define STATVFS_F_FLAG(vfs) (vfs).f_flag
103 #define STATVFS_F_FLAG(vfs) (vfs).f_flags
106 #if defined(__FreeBSD__) || defined(__NetBSD__)
107 #include <sys/sysctl.h>
110 using namespace llvm;
115 #if defined(__Bitrig__) || defined(__OpenBSD__) || defined(__minix) || \
116 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__) || \
119 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
122 char fullpath[PATH_MAX];
124 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
125 if (!realpath(fullpath, ret))
127 if (stat(fullpath, &sb) != 0)
134 getprogpath(char ret[PATH_MAX], const char *bin)
138 /* First approach: absolute path. */
140 if (test_dir(ret, "/", bin) == 0)
145 /* Second approach: relative path. */
146 if (strchr(bin, '/')) {
148 if (!getcwd(cwd, PATH_MAX))
150 if (test_dir(ret, cwd, bin) == 0)
155 /* Third approach: $PATH */
156 if ((pv = getenv("PATH")) == nullptr)
161 while ((t = strsep(&s, ":")) != nullptr) {
162 if (test_dir(ret, t, bin) == 0) {
170 #endif // Bitrig || OpenBSD || minix || linux || CYGWIN || DragonFly || AIX
172 /// GetMainExecutable - Return the path to the main executable, given the
173 /// value of argv[0] from program startup.
174 std::string getMainExecutable(const char *argv0, void *MainAddr) {
175 #if defined(__APPLE__)
176 // On OS X the executable path is saved to the stack by dyld. Reading it
177 // from there is much faster than calling dladdr, especially for large
178 // binaries with symbols.
179 char exe_path[MAXPATHLEN];
180 uint32_t size = sizeof(exe_path);
181 if (_NSGetExecutablePath(exe_path, &size) == 0) {
182 char link_path[MAXPATHLEN];
183 if (realpath(exe_path, link_path))
186 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
189 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
191 mib[2] = KERN_PROC_PATHNAME;
194 mib[1] = KERN_PROC_ARGS;
196 mib[3] = KERN_PROC_PATHNAME;
198 char exe_path[PATH_MAX];
199 size_t cb = sizeof(exe_path);
200 if (sysctl(mib, 4, exe_path, &cb, NULL, 0) == 0)
202 #elif defined(__Bitrig__) || defined(__OpenBSD__) || defined(__minix) || \
203 defined(__DragonFly__) || defined(_AIX)
204 char exe_path[PATH_MAX];
206 if (getprogpath(exe_path, argv0) != NULL)
208 #elif defined(__linux__) || defined(__CYGWIN__)
209 char exe_path[MAXPATHLEN];
210 StringRef aPath("/proc/self/exe");
211 if (sys::fs::exists(aPath)) {
212 // /proc is not always mounted under Linux (chroot for example).
213 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
215 return std::string(exe_path, len);
217 // Fall back to the classical detection.
218 if (getprogpath(exe_path, argv0))
221 #elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
222 // Use dladdr to get executable path if available.
224 int err = dladdr(MainAddr, &DLInfo);
228 // If the filename is a symlink, we need to resolve and return the location of
229 // the actual executable.
230 char link_path[MAXPATHLEN];
231 if (realpath(DLInfo.dli_fname, link_path))
234 #error GetMainExecutable is not implemented on this host yet.
239 TimePoint<> file_status::getLastAccessedTime() const {
240 return toTimePoint(fs_st_atime);
243 TimePoint<> file_status::getLastModificationTime() const {
244 return toTimePoint(fs_st_mtime);
247 UniqueID file_status::getUniqueID() const {
248 return UniqueID(fs_st_dev, fs_st_ino);
251 uint32_t file_status::getLinkCount() const {
255 ErrorOr<space_info> disk_space(const Twine &Path) {
257 if (::STATVFS(Path.str().c_str(), &Vfs))
258 return std::error_code(errno, std::generic_category());
259 auto FrSize = STATVFS_F_FRSIZE(Vfs);
260 space_info SpaceInfo;
261 SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
262 SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
263 SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
267 std::error_code current_path(SmallVectorImpl<char> &result) {
270 const char *pwd = ::getenv("PWD");
271 llvm::sys::fs::file_status PWDStatus, DotStatus;
272 if (pwd && llvm::sys::path::is_absolute(pwd) &&
273 !llvm::sys::fs::status(pwd, PWDStatus) &&
274 !llvm::sys::fs::status(".", DotStatus) &&
275 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
276 result.append(pwd, pwd + strlen(pwd));
277 return std::error_code();
281 result.reserve(MAXPATHLEN);
284 result.reserve(1024);
288 if (::getcwd(result.data(), result.capacity()) == nullptr) {
289 // See if there was a real error.
291 return std::error_code(errno, std::generic_category());
292 // Otherwise there just wasn't enough space.
293 result.reserve(result.capacity() * 2);
298 result.set_size(strlen(result.data()));
299 return std::error_code();
302 std::error_code set_current_path(const Twine &path) {
303 SmallString<128> path_storage;
304 StringRef p = path.toNullTerminatedStringRef(path_storage);
306 if (::chdir(p.begin()) == -1)
307 return std::error_code(errno, std::generic_category());
309 return std::error_code();
312 std::error_code create_directory(const Twine &path, bool IgnoreExisting,
314 SmallString<128> path_storage;
315 StringRef p = path.toNullTerminatedStringRef(path_storage);
317 if (::mkdir(p.begin(), Perms) == -1) {
318 if (errno != EEXIST || !IgnoreExisting)
319 return std::error_code(errno, std::generic_category());
322 return std::error_code();
325 // Note that we are using symbolic link because hard links are not supported by
326 // all filesystems (SMB doesn't).
327 std::error_code create_link(const Twine &to, const Twine &from) {
329 SmallString<128> from_storage;
330 SmallString<128> to_storage;
331 StringRef f = from.toNullTerminatedStringRef(from_storage);
332 StringRef t = to.toNullTerminatedStringRef(to_storage);
334 if (::symlink(t.begin(), f.begin()) == -1)
335 return std::error_code(errno, std::generic_category());
337 return std::error_code();
340 std::error_code create_hard_link(const Twine &to, const Twine &from) {
342 SmallString<128> from_storage;
343 SmallString<128> to_storage;
344 StringRef f = from.toNullTerminatedStringRef(from_storage);
345 StringRef t = to.toNullTerminatedStringRef(to_storage);
347 if (::link(t.begin(), f.begin()) == -1)
348 return std::error_code(errno, std::generic_category());
350 return std::error_code();
353 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
354 SmallString<128> path_storage;
355 StringRef p = path.toNullTerminatedStringRef(path_storage);
358 if (lstat(p.begin(), &buf) != 0) {
359 if (errno != ENOENT || !IgnoreNonExisting)
360 return std::error_code(errno, std::generic_category());
361 return std::error_code();
364 // Note: this check catches strange situations. In all cases, LLVM should
365 // only be involved in the creation and deletion of regular files. This
366 // check ensures that what we're trying to erase is a regular file. It
367 // effectively prevents LLVM from erasing things like /dev/null, any block
368 // special file, or other things that aren't "regular" files.
369 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
370 return make_error_code(errc::operation_not_permitted);
372 if (::remove(p.begin()) == -1) {
373 if (errno != ENOENT || !IgnoreNonExisting)
374 return std::error_code(errno, std::generic_category());
377 return std::error_code();
380 static bool is_local_impl(struct STATVFS &Vfs) {
381 #if defined(__linux__)
382 #ifndef NFS_SUPER_MAGIC
383 #define NFS_SUPER_MAGIC 0x6969
385 #ifndef SMB_SUPER_MAGIC
386 #define SMB_SUPER_MAGIC 0x517B
388 #ifndef CIFS_MAGIC_NUMBER
389 #define CIFS_MAGIC_NUMBER 0xFF534D42
391 switch ((uint32_t)Vfs.f_type) {
392 case NFS_SUPER_MAGIC:
393 case SMB_SUPER_MAGIC:
394 case CIFS_MAGIC_NUMBER:
399 #elif defined(__CYGWIN__)
400 // Cygwin doesn't expose this information; would need to use Win32 API.
403 return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
407 std::error_code is_local(const Twine &Path, bool &Result) {
409 if (::STATVFS(Path.str().c_str(), &Vfs))
410 return std::error_code(errno, std::generic_category());
412 Result = is_local_impl(Vfs);
413 return std::error_code();
416 std::error_code is_local(int FD, bool &Result) {
418 if (::FSTATVFS(FD, &Vfs))
419 return std::error_code(errno, std::generic_category());
421 Result = is_local_impl(Vfs);
422 return std::error_code();
425 std::error_code rename(const Twine &from, const Twine &to) {
427 SmallString<128> from_storage;
428 SmallString<128> to_storage;
429 StringRef f = from.toNullTerminatedStringRef(from_storage);
430 StringRef t = to.toNullTerminatedStringRef(to_storage);
432 if (::rename(f.begin(), t.begin()) == -1)
433 return std::error_code(errno, std::generic_category());
435 return std::error_code();
438 std::error_code resize_file(int FD, uint64_t Size) {
439 #if defined(HAVE_POSIX_FALLOCATE)
440 // If we have posix_fallocate use it. Unlike ftruncate it always allocates
441 // space, so we get an error if the disk is full.
442 if (int Err = ::posix_fallocate(FD, 0, Size)) {
443 if (Err != EOPNOTSUPP)
444 return std::error_code(Err, std::generic_category());
447 // Use ftruncate as a fallback. It may or may not allocate space. At least on
448 // OS X with HFS+ it does.
449 if (::ftruncate(FD, Size) == -1)
450 return std::error_code(errno, std::generic_category());
452 return std::error_code();
455 static int convertAccessMode(AccessMode Mode) {
457 case AccessMode::Exist:
459 case AccessMode::Write:
461 case AccessMode::Execute:
462 return R_OK | X_OK; // scripts also need R_OK.
464 llvm_unreachable("invalid enum");
467 std::error_code access(const Twine &Path, AccessMode Mode) {
468 SmallString<128> PathStorage;
469 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
471 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
472 return std::error_code(errno, std::generic_category());
474 if (Mode == AccessMode::Execute) {
475 // Don't say that directories are executable.
477 if (0 != stat(P.begin(), &buf))
478 return errc::permission_denied;
479 if (!S_ISREG(buf.st_mode))
480 return errc::permission_denied;
483 return std::error_code();
486 bool can_execute(const Twine &Path) {
487 return !access(Path, AccessMode::Execute);
490 bool equivalent(file_status A, file_status B) {
491 assert(status_known(A) && status_known(B));
492 return A.fs_st_dev == B.fs_st_dev &&
493 A.fs_st_ino == B.fs_st_ino;
496 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
497 file_status fsA, fsB;
498 if (std::error_code ec = status(A, fsA))
500 if (std::error_code ec = status(B, fsB))
502 result = equivalent(fsA, fsB);
503 return std::error_code();
506 static void expandTildeExpr(SmallVectorImpl<char> &Path) {
507 StringRef PathStr(Path.begin(), Path.size());
508 if (PathStr.empty() || !PathStr.startswith("~"))
511 PathStr = PathStr.drop_front();
513 PathStr.take_until([](char c) { return path::is_separator(c); });
514 StringRef Remainder = PathStr.substr(Expr.size() + 1);
515 SmallString<128> Storage;
517 // This is just ~/..., resolve it to the current user's home dir.
518 if (!path::home_directory(Storage)) {
519 // For some reason we couldn't get the home directory. Just exit.
523 // Overwrite the first character and insert the rest.
524 Path[0] = Storage[0];
525 Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
529 // This is a string of the form ~username/, look up this user's entry in the
530 // password database.
531 struct passwd *Entry = nullptr;
532 std::string User = Expr.str();
533 Entry = ::getpwnam(User.c_str());
536 // Unable to look up the entry, just return back the original path.
542 Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
543 llvm::sys::path::append(Path, Storage);
546 static std::error_code fillStatus(int StatRet, const struct stat &Status,
547 file_status &Result) {
549 std::error_code ec(errno, std::generic_category());
550 if (ec == errc::no_such_file_or_directory)
551 Result = file_status(file_type::file_not_found);
553 Result = file_status(file_type::status_error);
557 file_type Type = file_type::type_unknown;
559 if (S_ISDIR(Status.st_mode))
560 Type = file_type::directory_file;
561 else if (S_ISREG(Status.st_mode))
562 Type = file_type::regular_file;
563 else if (S_ISBLK(Status.st_mode))
564 Type = file_type::block_file;
565 else if (S_ISCHR(Status.st_mode))
566 Type = file_type::character_file;
567 else if (S_ISFIFO(Status.st_mode))
568 Type = file_type::fifo_file;
569 else if (S_ISSOCK(Status.st_mode))
570 Type = file_type::socket_file;
571 else if (S_ISLNK(Status.st_mode))
572 Type = file_type::symlink_file;
574 perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
575 Result = file_status(Type, Perms, Status.st_dev, Status.st_nlink,
576 Status.st_ino, Status.st_atime, Status.st_mtime,
577 Status.st_uid, Status.st_gid, Status.st_size);
579 return std::error_code();
582 std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
583 SmallString<128> PathStorage;
584 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
587 int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
588 return fillStatus(StatRet, Status, Result);
591 std::error_code status(int FD, file_status &Result) {
593 int StatRet = ::fstat(FD, &Status);
594 return fillStatus(StatRet, Status, Result);
597 std::error_code setPermissions(const Twine &Path, perms Permissions) {
598 SmallString<128> PathStorage;
599 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
601 if (::chmod(P.begin(), Permissions))
602 return std::error_code(errno, std::generic_category());
603 return std::error_code();
606 std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time) {
607 #if defined(HAVE_FUTIMENS)
609 Times[0] = Times[1] = sys::toTimeSpec(Time);
610 if (::futimens(FD, Times))
611 return std::error_code(errno, std::generic_category());
612 return std::error_code();
613 #elif defined(HAVE_FUTIMES)
615 Times[0] = Times[1] = sys::toTimeVal(
616 std::chrono::time_point_cast<std::chrono::microseconds>(Time));
617 if (::futimes(FD, Times))
618 return std::error_code(errno, std::generic_category());
619 return std::error_code();
621 #warning Missing futimes() and futimens()
622 return make_error_code(errc::function_not_supported);
626 std::error_code mapped_file_region::init(int FD, uint64_t Offset,
630 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
631 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
632 #if defined(__APPLE__)
633 //----------------------------------------------------------------------
634 // Newer versions of MacOSX have a flag that will allow us to read from
635 // binaries whose code signature is invalid without crashing by using
636 // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
637 // is mapped we can avoid crashing and return zeroes to any pages we try
638 // to read if the media becomes unavailable by using the
639 // MAP_RESILIENT_MEDIA flag. These flags are only usable when mapping
640 // with PROT_READ, so take care not to specify them otherwise.
641 //----------------------------------------------------------------------
642 if (Mode == readonly) {
643 #if defined(MAP_RESILIENT_CODESIGN)
644 flags |= MAP_RESILIENT_CODESIGN;
646 #if defined(MAP_RESILIENT_MEDIA)
647 flags |= MAP_RESILIENT_MEDIA;
650 #endif // #if defined (__APPLE__)
652 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
653 if (Mapping == MAP_FAILED)
654 return std::error_code(errno, std::generic_category());
655 return std::error_code();
658 mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
659 uint64_t offset, std::error_code &ec)
660 : Size(length), Mapping() {
661 // Make sure that the requested size fits within SIZE_T.
662 if (length > std::numeric_limits<size_t>::max()) {
663 ec = make_error_code(errc::invalid_argument);
667 ec = init(fd, offset, mode);
672 mapped_file_region::~mapped_file_region() {
674 ::munmap(Mapping, Size);
677 uint64_t mapped_file_region::size() const {
678 assert(Mapping && "Mapping failed but used anyway!");
682 char *mapped_file_region::data() const {
683 assert(Mapping && "Mapping failed but used anyway!");
684 return reinterpret_cast<char*>(Mapping);
687 const char *mapped_file_region::const_data() const {
688 assert(Mapping && "Mapping failed but used anyway!");
689 return reinterpret_cast<const char*>(Mapping);
692 int mapped_file_region::alignment() {
693 return Process::getPageSize();
696 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
698 bool follow_symlinks) {
699 SmallString<128> path_null(path);
700 DIR *directory = ::opendir(path_null.c_str());
702 return std::error_code(errno, std::generic_category());
704 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
705 // Add something for replace_filename to replace.
706 path::append(path_null, ".");
707 it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
708 return directory_iterator_increment(it);
711 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
712 if (it.IterationHandle)
713 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
714 it.IterationHandle = 0;
715 it.CurrentEntry = directory_entry();
716 return std::error_code();
719 std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
721 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
722 if (cur_dir == nullptr && errno != 0) {
723 return std::error_code(errno, std::generic_category());
724 } else if (cur_dir != nullptr) {
725 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
726 if ((name.size() == 1 && name[0] == '.') ||
727 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
728 return directory_iterator_increment(it);
729 it.CurrentEntry.replace_filename(name);
731 return directory_iterator_destruct(it);
733 return std::error_code();
736 #if !defined(F_GETPATH)
737 static bool hasProcSelfFD() {
738 // If we have a /proc filesystem mounted, we can quickly establish the
739 // real name of the file with readlink
740 static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
745 std::error_code openFileForRead(const Twine &Name, int &ResultFD,
746 SmallVectorImpl<char> *RealPath) {
747 SmallString<128> Storage;
748 StringRef P = Name.toNullTerminatedStringRef(Storage);
749 int OpenFlags = O_RDONLY;
751 OpenFlags |= O_CLOEXEC;
753 while ((ResultFD = open(P.begin(), OpenFlags)) < 0) {
755 return std::error_code(errno, std::generic_category());
758 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
760 assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
762 // Attempt to get the real name of the file, if the user asked
764 return std::error_code();
766 #if defined(F_GETPATH)
767 // When F_GETPATH is availble, it is the quickest way to get
768 // the real path name.
769 char Buffer[MAXPATHLEN];
770 if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
771 RealPath->append(Buffer, Buffer + strlen(Buffer));
773 char Buffer[PATH_MAX];
774 if (hasProcSelfFD()) {
776 snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
777 ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
779 RealPath->append(Buffer, Buffer + CharCount);
781 // Use ::realpath to get the real path name
782 if (::realpath(P.begin(), Buffer) != nullptr)
783 RealPath->append(Buffer, Buffer + strlen(Buffer));
786 return std::error_code();
789 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
790 sys::fs::OpenFlags Flags, unsigned Mode) {
791 // Verify that we don't have both "append" and "excl".
792 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
793 "Cannot specify both 'excl' and 'append' file creation flags!");
795 int OpenFlags = O_CREAT;
798 OpenFlags |= O_CLOEXEC;
804 OpenFlags |= O_WRONLY;
806 if (Flags & F_Append)
807 OpenFlags |= O_APPEND;
809 OpenFlags |= O_TRUNC;
814 SmallString<128> Storage;
815 StringRef P = Name.toNullTerminatedStringRef(Storage);
816 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
818 return std::error_code(errno, std::generic_category());
821 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
823 assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
825 return std::error_code();
828 std::error_code getPathFromOpenFD(int FD, SmallVectorImpl<char> &ResultPath) {
830 return make_error_code(errc::bad_file_descriptor);
832 #if defined(F_GETPATH)
833 // When F_GETPATH is availble, it is the quickest way to get
834 // the path from a file descriptor.
835 ResultPath.reserve(MAXPATHLEN);
836 if (::fcntl(FD, F_GETPATH, ResultPath.begin()) == -1)
837 return std::error_code(errno, std::generic_category());
839 ResultPath.set_size(strlen(ResultPath.begin()));
841 // If we have a /proc filesystem mounted, we can quickly establish the
842 // real name of the file with readlink. Otherwise, we don't know how to
843 // get the filename from a file descriptor. Give up.
844 if (!fs::hasProcSelfFD())
845 return make_error_code(errc::function_not_supported);
847 ResultPath.reserve(PATH_MAX);
849 snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", FD);
850 ssize_t CharCount = ::readlink(ProcPath, ResultPath.begin(), ResultPath.capacity());
852 return std::error_code(errno, std::generic_category());
854 // Was the filename truncated?
855 if (static_cast<size_t>(CharCount) == ResultPath.capacity()) {
856 // Use lstat to get the size of the filename
858 if (::lstat(ProcPath, &sb) < 0)
859 return std::error_code(errno, std::generic_category());
861 ResultPath.reserve(sb.st_size + 1);
862 CharCount = ::readlink(ProcPath, ResultPath.begin(), ResultPath.capacity());
864 return std::error_code(errno, std::generic_category());
866 // Test for race condition: did the link size change?
867 if (CharCount > sb.st_size)
868 return std::error_code(ENAMETOOLONG, std::generic_category());
870 ResultPath.set_size(static_cast<size_t>(CharCount));
872 return std::error_code();
875 template <typename T>
876 static std::error_code remove_directories_impl(const T &Entry,
879 directory_iterator Begin(Entry, EC, false);
880 directory_iterator End;
881 while (Begin != End) {
884 EC = Item.status(st);
885 if (EC && !IgnoreErrors)
888 if (is_directory(st)) {
889 EC = remove_directories_impl(Item, IgnoreErrors);
890 if (EC && !IgnoreErrors)
894 EC = fs::remove(Item.path(), true);
895 if (EC && !IgnoreErrors)
899 if (EC && !IgnoreErrors)
902 return std::error_code();
905 std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
906 auto EC = remove_directories_impl(path, IgnoreErrors);
907 if (EC && !IgnoreErrors)
909 EC = fs::remove(path, true);
910 if (EC && !IgnoreErrors)
912 return std::error_code();
915 std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
918 if (path.isTriviallyEmpty())
919 return std::error_code();
922 SmallString<128> Storage;
923 path.toVector(Storage);
924 expandTildeExpr(Storage);
925 return real_path(Storage, dest, false);
929 std::error_code EC = openFileForRead(path, fd, &dest);
934 return std::error_code();
937 } // end namespace fs
941 bool home_directory(SmallVectorImpl<char> &result) {
942 char *RequestedDir = getenv("HOME");
944 struct passwd *pw = getpwuid(getuid());
945 if (pw && pw->pw_dir)
946 RequestedDir = pw->pw_dir;
952 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
956 static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
957 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
958 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
959 // macros defined in <unistd.h> on darwin >= 9
960 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
961 : _CS_DARWIN_USER_CACHE_DIR;
962 size_t ConfLen = confstr(ConfName, nullptr, 0);
965 Result.resize(ConfLen);
966 ConfLen = confstr(ConfName, Result.data(), Result.size());
967 } while (ConfLen > 0 && ConfLen != Result.size());
970 assert(Result.back() == 0);
981 static bool getUserCacheDir(SmallVectorImpl<char> &Result) {
982 // First try using XDG_CACHE_HOME env variable,
983 // as specified in XDG Base Directory Specification at
984 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
985 if (const char *XdgCacheDir = std::getenv("XDG_CACHE_HOME")) {
987 Result.append(XdgCacheDir, XdgCacheDir + strlen(XdgCacheDir));
991 // Try Darwin configuration query
992 if (getDarwinConfDir(false, Result))
995 // Use "$HOME/.cache" if $HOME is available
996 if (home_directory(Result)) {
997 append(Result, ".cache");
1004 static const char *getEnvTempDir() {
1005 // Check whether the temporary directory is specified by an environment
1007 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1008 for (const char *Env : EnvironmentVariables) {
1009 if (const char *Dir = std::getenv(Env))
1016 static const char *getDefaultTempDir(bool ErasedOnReboot) {
1027 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1030 if (ErasedOnReboot) {
1031 // There is no env variable for the cache directory.
1032 if (const char *RequestedDir = getEnvTempDir()) {
1033 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1038 if (getDarwinConfDir(ErasedOnReboot, Result))
1041 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1042 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1045 } // end namespace path
1047 } // end namespace sys
1048 } // end namespace llvm