1 //===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the Unix specific implementation of the Path API.
11 //===----------------------------------------------------------------------===//
13 //===----------------------------------------------------------------------===//
14 //=== WARNING: Implementation here must contain only generic UNIX code that
15 //=== is guaranteed to work on *all* UNIX variants.
16 //===----------------------------------------------------------------------===//
30 #ifdef HAVE_SYS_MMAN_H
38 #include <mach-o/dyld.h>
40 #elif defined(__DragonFly__)
41 #include <sys/mount.h>
44 // Both stdio.h and cstdio are included via different paths and
45 // stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
51 #if defined(__GNU__) && !defined(PATH_MAX)
52 # define PATH_MAX 4096
53 # define MAXPATHLEN 4096
56 #include <sys/types.h>
57 #if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && \
58 !defined(__linux__) && !defined(__FreeBSD_kernel__)
59 #include <sys/statvfs.h>
60 #define STATVFS statvfs
61 #define FSTATVFS fstatvfs
62 #define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
64 #if defined(__OpenBSD__) || defined(__FreeBSD__)
65 #include <sys/mount.h>
66 #include <sys/param.h>
67 #elif defined(__linux__)
68 #if defined(HAVE_LINUX_MAGIC_H)
69 #include <linux/magic.h>
71 #if defined(HAVE_LINUX_NFS_FS_H)
72 #include <linux/nfs_fs.h>
74 #if defined(HAVE_LINUX_SMB_H)
75 #include <linux/smb.h>
80 #include <sys/mount.h>
82 #define STATVFS statfs
83 #define FSTATVFS fstatfs
84 #define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
87 #if defined(__NetBSD__) || defined(__DragonFly__) || defined(__GNU__)
88 #define STATVFS_F_FLAG(vfs) (vfs).f_flag
90 #define STATVFS_F_FLAG(vfs) (vfs).f_flags
99 const file_t kInvalidFile = -1;
101 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
102 defined(__minix) || defined(__FreeBSD_kernel__) || defined(__linux__) || \
103 defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX) || defined(__GNU__)
105 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
108 char fullpath[PATH_MAX];
110 int chars = snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
111 // We cannot write PATH_MAX characters because the string will be terminated
112 // with a null character. Fail if truncation happened.
113 if (chars >= PATH_MAX)
115 if (!realpath(fullpath, ret))
117 if (stat(fullpath, &sb) != 0)
124 getprogpath(char ret[PATH_MAX], const char *bin)
128 /* First approach: absolute path. */
130 if (test_dir(ret, "/", bin) == 0)
135 /* Second approach: relative path. */
136 if (strchr(bin, '/')) {
138 if (!getcwd(cwd, PATH_MAX))
140 if (test_dir(ret, cwd, bin) == 0)
145 /* Third approach: $PATH */
146 if ((pv = getenv("PATH")) == nullptr)
151 while ((t = strsep(&s, ":")) != nullptr) {
152 if (test_dir(ret, t, bin) == 0) {
160 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
162 /// GetMainExecutable - Return the path to the main executable, given the
163 /// value of argv[0] from program startup.
164 std::string getMainExecutable(const char *argv0, void *MainAddr) {
165 #if defined(__APPLE__)
166 // On OS X the executable path is saved to the stack by dyld. Reading it
167 // from there is much faster than calling dladdr, especially for large
168 // binaries with symbols.
169 char exe_path[MAXPATHLEN];
170 uint32_t size = sizeof(exe_path);
171 if (_NSGetExecutablePath(exe_path, &size) == 0) {
172 char link_path[MAXPATHLEN];
173 if (realpath(exe_path, link_path))
176 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
177 defined(__minix) || defined(__DragonFly__) || \
178 defined(__FreeBSD_kernel__) || defined(_AIX)
179 char exe_path[PATH_MAX];
181 if (getprogpath(exe_path, argv0) != NULL)
183 #elif defined(__linux__) || defined(__CYGWIN__)
184 char exe_path[MAXPATHLEN];
185 StringRef aPath("/proc/self/exe");
186 if (sys::fs::exists(aPath)) {
187 // /proc is not always mounted under Linux (chroot for example).
188 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
192 // Null terminate the string for realpath. readlink never null
193 // terminates its output.
194 len = std::min(len, ssize_t(sizeof(exe_path) - 1));
195 exe_path[len] = '\0';
197 // On Linux, /proc/self/exe always looks through symlinks. However, on
198 // GNU/Hurd, /proc/self/exe is a symlink to the path that was used to start
199 // the program, and not the eventual binary file. Therefore, call realpath
200 // so this behaves the same on all platforms.
201 #if _POSIX_VERSION >= 200112 || defined(__GLIBC__)
202 char *real_path = realpath(exe_path, NULL);
203 std::string ret = std::string(real_path);
207 char real_path[MAXPATHLEN];
208 realpath(exe_path, real_path);
209 return std::string(real_path);
212 // Fall back to the classical detection.
213 if (getprogpath(exe_path, argv0))
216 #elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
217 // Use dladdr to get executable path if available.
219 int err = dladdr(MainAddr, &DLInfo);
223 // If the filename is a symlink, we need to resolve and return the location of
224 // the actual executable.
225 char link_path[MAXPATHLEN];
226 if (realpath(DLInfo.dli_fname, link_path))
229 #error GetMainExecutable is not implemented on this host yet.
234 TimePoint<> basic_file_status::getLastAccessedTime() const {
235 return toTimePoint(fs_st_atime, fs_st_atime_nsec);
238 TimePoint<> basic_file_status::getLastModificationTime() const {
239 return toTimePoint(fs_st_mtime, fs_st_mtime_nsec);
242 UniqueID file_status::getUniqueID() const {
243 return UniqueID(fs_st_dev, fs_st_ino);
246 uint32_t file_status::getLinkCount() const {
250 ErrorOr<space_info> disk_space(const Twine &Path) {
252 if (::STATVFS(Path.str().c_str(), &Vfs))
253 return std::error_code(errno, std::generic_category());
254 auto FrSize = STATVFS_F_FRSIZE(Vfs);
255 space_info SpaceInfo;
256 SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
257 SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
258 SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
262 std::error_code current_path(SmallVectorImpl<char> &result) {
265 const char *pwd = ::getenv("PWD");
266 llvm::sys::fs::file_status PWDStatus, DotStatus;
267 if (pwd && llvm::sys::path::is_absolute(pwd) &&
268 !llvm::sys::fs::status(pwd, PWDStatus) &&
269 !llvm::sys::fs::status(".", DotStatus) &&
270 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
271 result.append(pwd, pwd + strlen(pwd));
272 return std::error_code();
276 result.reserve(MAXPATHLEN);
279 result.reserve(1024);
283 if (::getcwd(result.data(), result.capacity()) == nullptr) {
284 // See if there was a real error.
286 return std::error_code(errno, std::generic_category());
287 // Otherwise there just wasn't enough space.
288 result.reserve(result.capacity() * 2);
293 result.set_size(strlen(result.data()));
294 return std::error_code();
297 std::error_code set_current_path(const Twine &path) {
298 SmallString<128> path_storage;
299 StringRef p = path.toNullTerminatedStringRef(path_storage);
301 if (::chdir(p.begin()) == -1)
302 return std::error_code(errno, std::generic_category());
304 return std::error_code();
307 std::error_code create_directory(const Twine &path, bool IgnoreExisting,
309 SmallString<128> path_storage;
310 StringRef p = path.toNullTerminatedStringRef(path_storage);
312 if (::mkdir(p.begin(), Perms) == -1) {
313 if (errno != EEXIST || !IgnoreExisting)
314 return std::error_code(errno, std::generic_category());
317 return std::error_code();
320 // Note that we are using symbolic link because hard links are not supported by
321 // all filesystems (SMB doesn't).
322 std::error_code create_link(const Twine &to, const Twine &from) {
324 SmallString<128> from_storage;
325 SmallString<128> to_storage;
326 StringRef f = from.toNullTerminatedStringRef(from_storage);
327 StringRef t = to.toNullTerminatedStringRef(to_storage);
329 if (::symlink(t.begin(), f.begin()) == -1)
330 return std::error_code(errno, std::generic_category());
332 return std::error_code();
335 std::error_code create_hard_link(const Twine &to, const Twine &from) {
337 SmallString<128> from_storage;
338 SmallString<128> to_storage;
339 StringRef f = from.toNullTerminatedStringRef(from_storage);
340 StringRef t = to.toNullTerminatedStringRef(to_storage);
342 if (::link(t.begin(), f.begin()) == -1)
343 return std::error_code(errno, std::generic_category());
345 return std::error_code();
348 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
349 SmallString<128> path_storage;
350 StringRef p = path.toNullTerminatedStringRef(path_storage);
353 if (lstat(p.begin(), &buf) != 0) {
354 if (errno != ENOENT || !IgnoreNonExisting)
355 return std::error_code(errno, std::generic_category());
356 return std::error_code();
359 // Note: this check catches strange situations. In all cases, LLVM should
360 // only be involved in the creation and deletion of regular files. This
361 // check ensures that what we're trying to erase is a regular file. It
362 // effectively prevents LLVM from erasing things like /dev/null, any block
363 // special file, or other things that aren't "regular" files.
364 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
365 return make_error_code(errc::operation_not_permitted);
367 if (::remove(p.begin()) == -1) {
368 if (errno != ENOENT || !IgnoreNonExisting)
369 return std::error_code(errno, std::generic_category());
372 return std::error_code();
375 static bool is_local_impl(struct STATVFS &Vfs) {
376 #if defined(__linux__) || defined(__GNU__)
377 #ifndef NFS_SUPER_MAGIC
378 #define NFS_SUPER_MAGIC 0x6969
380 #ifndef SMB_SUPER_MAGIC
381 #define SMB_SUPER_MAGIC 0x517B
383 #ifndef CIFS_MAGIC_NUMBER
384 #define CIFS_MAGIC_NUMBER 0xFF534D42
387 switch ((uint32_t)Vfs.__f_type) {
389 switch ((uint32_t)Vfs.f_type) {
391 case NFS_SUPER_MAGIC:
392 case SMB_SUPER_MAGIC:
393 case CIFS_MAGIC_NUMBER:
398 #elif defined(__CYGWIN__)
399 // Cygwin doesn't expose this information; would need to use Win32 API.
401 #elif defined(__Fuchsia__)
402 // Fuchsia doesn't yet support remote filesystem mounts.
404 #elif defined(__HAIKU__)
405 // Haiku doesn't expose this information.
408 // statvfs::f_basetype contains a null-terminated FSType name of the mounted target
409 StringRef fstype(Vfs.f_basetype);
410 // NFS is the only non-local fstype??
411 return !fstype.equals("nfs");
413 return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
417 std::error_code is_local(const Twine &Path, bool &Result) {
419 if (::STATVFS(Path.str().c_str(), &Vfs))
420 return std::error_code(errno, std::generic_category());
422 Result = is_local_impl(Vfs);
423 return std::error_code();
426 std::error_code is_local(int FD, bool &Result) {
428 if (::FSTATVFS(FD, &Vfs))
429 return std::error_code(errno, std::generic_category());
431 Result = is_local_impl(Vfs);
432 return std::error_code();
435 std::error_code rename(const Twine &from, const Twine &to) {
437 SmallString<128> from_storage;
438 SmallString<128> to_storage;
439 StringRef f = from.toNullTerminatedStringRef(from_storage);
440 StringRef t = to.toNullTerminatedStringRef(to_storage);
442 if (::rename(f.begin(), t.begin()) == -1)
443 return std::error_code(errno, std::generic_category());
445 return std::error_code();
448 std::error_code resize_file(int FD, uint64_t Size) {
449 #if defined(HAVE_POSIX_FALLOCATE)
450 // If we have posix_fallocate use it. Unlike ftruncate it always allocates
451 // space, so we get an error if the disk is full.
452 if (int Err = ::posix_fallocate(FD, 0, Size)) {
453 if (Err != EINVAL && Err != EOPNOTSUPP)
454 return std::error_code(Err, std::generic_category());
457 // Use ftruncate as a fallback. It may or may not allocate space. At least on
458 // OS X with HFS+ it does.
459 if (::ftruncate(FD, Size) == -1)
460 return std::error_code(errno, std::generic_category());
462 return std::error_code();
465 static int convertAccessMode(AccessMode Mode) {
467 case AccessMode::Exist:
469 case AccessMode::Write:
471 case AccessMode::Execute:
472 return R_OK | X_OK; // scripts also need R_OK.
474 llvm_unreachable("invalid enum");
477 std::error_code access(const Twine &Path, AccessMode Mode) {
478 SmallString<128> PathStorage;
479 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
481 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
482 return std::error_code(errno, std::generic_category());
484 if (Mode == AccessMode::Execute) {
485 // Don't say that directories are executable.
487 if (0 != stat(P.begin(), &buf))
488 return errc::permission_denied;
489 if (!S_ISREG(buf.st_mode))
490 return errc::permission_denied;
493 return std::error_code();
496 bool can_execute(const Twine &Path) {
497 return !access(Path, AccessMode::Execute);
500 bool equivalent(file_status A, file_status B) {
501 assert(status_known(A) && status_known(B));
502 return A.fs_st_dev == B.fs_st_dev &&
503 A.fs_st_ino == B.fs_st_ino;
506 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
507 file_status fsA, fsB;
508 if (std::error_code ec = status(A, fsA))
510 if (std::error_code ec = status(B, fsB))
512 result = equivalent(fsA, fsB);
513 return std::error_code();
516 static void expandTildeExpr(SmallVectorImpl<char> &Path) {
517 StringRef PathStr(Path.begin(), Path.size());
518 if (PathStr.empty() || !PathStr.startswith("~"))
521 PathStr = PathStr.drop_front();
523 PathStr.take_until([](char c) { return path::is_separator(c); });
524 StringRef Remainder = PathStr.substr(Expr.size() + 1);
525 SmallString<128> Storage;
527 // This is just ~/..., resolve it to the current user's home dir.
528 if (!path::home_directory(Storage)) {
529 // For some reason we couldn't get the home directory. Just exit.
533 // Overwrite the first character and insert the rest.
534 Path[0] = Storage[0];
535 Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
539 // This is a string of the form ~username/, look up this user's entry in the
540 // password database.
541 struct passwd *Entry = nullptr;
542 std::string User = Expr.str();
543 Entry = ::getpwnam(User.c_str());
546 // Unable to look up the entry, just return back the original path.
552 Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
553 llvm::sys::path::append(Path, Storage);
557 void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
559 if (path.isTriviallyEmpty())
563 expandTildeExpr(dest);
568 static file_type typeForMode(mode_t Mode) {
570 return file_type::directory_file;
571 else if (S_ISREG(Mode))
572 return file_type::regular_file;
573 else if (S_ISBLK(Mode))
574 return file_type::block_file;
575 else if (S_ISCHR(Mode))
576 return file_type::character_file;
577 else if (S_ISFIFO(Mode))
578 return file_type::fifo_file;
579 else if (S_ISSOCK(Mode))
580 return file_type::socket_file;
581 else if (S_ISLNK(Mode))
582 return file_type::symlink_file;
583 return file_type::type_unknown;
586 static std::error_code fillStatus(int StatRet, const struct stat &Status,
587 file_status &Result) {
589 std::error_code EC(errno, std::generic_category());
590 if (EC == errc::no_such_file_or_directory)
591 Result = file_status(file_type::file_not_found);
593 Result = file_status(file_type::status_error);
597 uint32_t atime_nsec, mtime_nsec;
598 #if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
599 atime_nsec = Status.st_atimespec.tv_nsec;
600 mtime_nsec = Status.st_mtimespec.tv_nsec;
601 #elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
602 atime_nsec = Status.st_atim.tv_nsec;
603 mtime_nsec = Status.st_mtim.tv_nsec;
605 atime_nsec = mtime_nsec = 0;
608 perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
609 Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev,
610 Status.st_nlink, Status.st_ino,
611 Status.st_atime, atime_nsec, Status.st_mtime, mtime_nsec,
612 Status.st_uid, Status.st_gid, Status.st_size);
614 return std::error_code();
617 std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
618 SmallString<128> PathStorage;
619 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
622 int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
623 return fillStatus(StatRet, Status, Result);
626 std::error_code status(int FD, file_status &Result) {
628 int StatRet = ::fstat(FD, &Status);
629 return fillStatus(StatRet, Status, Result);
632 std::error_code setPermissions(const Twine &Path, perms Permissions) {
633 SmallString<128> PathStorage;
634 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
636 if (::chmod(P.begin(), Permissions))
637 return std::error_code(errno, std::generic_category());
638 return std::error_code();
641 std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
642 TimePoint<> ModificationTime) {
643 #if defined(HAVE_FUTIMENS)
645 Times[0] = sys::toTimeSpec(AccessTime);
646 Times[1] = sys::toTimeSpec(ModificationTime);
647 if (::futimens(FD, Times))
648 return std::error_code(errno, std::generic_category());
649 return std::error_code();
650 #elif defined(HAVE_FUTIMES)
652 Times[0] = sys::toTimeVal(
653 std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
655 sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
657 if (::futimes(FD, Times))
658 return std::error_code(errno, std::generic_category());
659 return std::error_code();
661 #warning Missing futimes() and futimens()
662 return make_error_code(errc::function_not_supported);
666 std::error_code mapped_file_region::init(int FD, uint64_t Offset,
670 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
671 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
672 #if defined(__APPLE__)
673 //----------------------------------------------------------------------
674 // Newer versions of MacOSX have a flag that will allow us to read from
675 // binaries whose code signature is invalid without crashing by using
676 // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
677 // is mapped we can avoid crashing and return zeroes to any pages we try
678 // to read if the media becomes unavailable by using the
679 // MAP_RESILIENT_MEDIA flag. These flags are only usable when mapping
680 // with PROT_READ, so take care not to specify them otherwise.
681 //----------------------------------------------------------------------
682 if (Mode == readonly) {
683 #if defined(MAP_RESILIENT_CODESIGN)
684 flags |= MAP_RESILIENT_CODESIGN;
686 #if defined(MAP_RESILIENT_MEDIA)
687 flags |= MAP_RESILIENT_MEDIA;
690 #endif // #if defined (__APPLE__)
692 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
693 if (Mapping == MAP_FAILED)
694 return std::error_code(errno, std::generic_category());
695 return std::error_code();
698 mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
699 uint64_t offset, std::error_code &ec)
700 : Size(length), Mapping(), Mode(mode) {
702 ec = init(fd, offset, mode);
707 mapped_file_region::~mapped_file_region() {
709 ::munmap(Mapping, Size);
712 size_t mapped_file_region::size() const {
713 assert(Mapping && "Mapping failed but used anyway!");
717 char *mapped_file_region::data() const {
718 assert(Mapping && "Mapping failed but used anyway!");
719 return reinterpret_cast<char*>(Mapping);
722 const char *mapped_file_region::const_data() const {
723 assert(Mapping && "Mapping failed but used anyway!");
724 return reinterpret_cast<const char*>(Mapping);
727 int mapped_file_region::alignment() {
728 return Process::getPageSize();
731 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
733 bool follow_symlinks) {
734 SmallString<128> path_null(path);
735 DIR *directory = ::opendir(path_null.c_str());
737 return std::error_code(errno, std::generic_category());
739 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
740 // Add something for replace_filename to replace.
741 path::append(path_null, ".");
742 it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
743 return directory_iterator_increment(it);
746 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
747 if (it.IterationHandle)
748 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
749 it.IterationHandle = 0;
750 it.CurrentEntry = directory_entry();
751 return std::error_code();
754 static file_type direntType(dirent* Entry) {
755 // Most platforms provide the file type in the dirent: Linux/BSD/Mac.
756 // The DTTOIF macro lets us reuse our status -> type conversion.
757 #if defined(_DIRENT_HAVE_D_TYPE) && defined(DTTOIF)
758 return typeForMode(DTTOIF(Entry->d_type));
760 // Other platforms such as Solaris require a stat() to get the type.
761 return file_type::type_unknown;
765 std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
767 dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));
768 if (CurDir == nullptr && errno != 0) {
769 return std::error_code(errno, std::generic_category());
770 } else if (CurDir != nullptr) {
771 StringRef Name(CurDir->d_name);
772 if ((Name.size() == 1 && Name[0] == '.') ||
773 (Name.size() == 2 && Name[0] == '.' && Name[1] == '.'))
774 return directory_iterator_increment(It);
775 It.CurrentEntry.replace_filename(Name, direntType(CurDir));
777 return directory_iterator_destruct(It);
779 return std::error_code();
782 ErrorOr<basic_file_status> directory_entry::status() const {
784 if (auto EC = fs::status(Path, s, FollowSymlinks))
789 #if !defined(F_GETPATH)
790 static bool hasProcSelfFD() {
791 // If we have a /proc filesystem mounted, we can quickly establish the
792 // real name of the file with readlink
793 static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
798 static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
801 if (Access == FA_Read)
803 else if (Access == FA_Write)
805 else if (Access == (FA_Read | FA_Write))
808 // This is for compatibility with old code that assumed F_Append implied
809 // would open an existing file. See Windows/Path.inc for a longer comment.
810 if (Flags & F_Append)
811 Disp = CD_OpenAlways;
813 if (Disp == CD_CreateNew) {
814 Result |= O_CREAT; // Create if it doesn't exist.
815 Result |= O_EXCL; // Fail if it does.
816 } else if (Disp == CD_CreateAlways) {
817 Result |= O_CREAT; // Create if it doesn't exist.
818 Result |= O_TRUNC; // Truncate if it does.
819 } else if (Disp == CD_OpenAlways) {
820 Result |= O_CREAT; // Create if it doesn't exist.
821 } else if (Disp == CD_OpenExisting) {
822 // Nothing special, just don't add O_CREAT and we get these semantics.
825 if (Flags & F_Append)
829 if (!(Flags & OF_ChildInherit))
836 std::error_code openFile(const Twine &Name, int &ResultFD,
837 CreationDisposition Disp, FileAccess Access,
838 OpenFlags Flags, unsigned Mode) {
839 int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
841 SmallString<128> Storage;
842 StringRef P = Name.toNullTerminatedStringRef(Storage);
843 // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
844 // when open is overloaded, such as in Bionic.
845 auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
846 if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
847 return std::error_code(errno, std::generic_category());
849 if (!(Flags & OF_ChildInherit)) {
850 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
852 assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
855 return std::error_code();
858 Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,
859 FileAccess Access, OpenFlags Flags,
863 std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
865 return errorCodeToError(EC);
869 std::error_code openFileForRead(const Twine &Name, int &ResultFD,
871 SmallVectorImpl<char> *RealPath) {
873 openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
877 // Attempt to get the real name of the file, if the user asked
879 return std::error_code();
881 #if defined(F_GETPATH)
882 // When F_GETPATH is availble, it is the quickest way to get
883 // the real path name.
884 char Buffer[MAXPATHLEN];
885 if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
886 RealPath->append(Buffer, Buffer + strlen(Buffer));
888 char Buffer[PATH_MAX];
889 if (hasProcSelfFD()) {
891 snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
892 ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
894 RealPath->append(Buffer, Buffer + CharCount);
896 SmallString<128> Storage;
897 StringRef P = Name.toNullTerminatedStringRef(Storage);
899 // Use ::realpath to get the real path name
900 if (::realpath(P.begin(), Buffer) != nullptr)
901 RealPath->append(Buffer, Buffer + strlen(Buffer));
904 return std::error_code();
907 Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
908 SmallVectorImpl<char> *RealPath) {
910 std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
912 return errorCodeToError(EC);
916 void closeFile(file_t &F) {
921 template <typename T>
922 static std::error_code remove_directories_impl(const T &Entry,
925 directory_iterator Begin(Entry, EC, false);
926 directory_iterator End;
927 while (Begin != End) {
929 ErrorOr<basic_file_status> st = Item.status();
930 if (!st && !IgnoreErrors)
931 return st.getError();
933 if (is_directory(*st)) {
934 EC = remove_directories_impl(Item, IgnoreErrors);
935 if (EC && !IgnoreErrors)
939 EC = fs::remove(Item.path(), true);
940 if (EC && !IgnoreErrors)
944 if (EC && !IgnoreErrors)
947 return std::error_code();
950 std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
951 auto EC = remove_directories_impl(path, IgnoreErrors);
952 if (EC && !IgnoreErrors)
954 EC = fs::remove(path, true);
955 if (EC && !IgnoreErrors)
957 return std::error_code();
960 std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
963 if (path.isTriviallyEmpty())
964 return std::error_code();
967 SmallString<128> Storage;
968 path.toVector(Storage);
969 expandTildeExpr(Storage);
970 return real_path(Storage, dest, false);
973 SmallString<128> Storage;
974 StringRef P = path.toNullTerminatedStringRef(Storage);
975 char Buffer[PATH_MAX];
976 if (::realpath(P.begin(), Buffer) == nullptr)
977 return std::error_code(errno, std::generic_category());
978 dest.append(Buffer, Buffer + strlen(Buffer));
979 return std::error_code();
982 } // end namespace fs
986 bool home_directory(SmallVectorImpl<char> &result) {
987 char *RequestedDir = getenv("HOME");
989 struct passwd *pw = getpwuid(getuid());
990 if (pw && pw->pw_dir)
991 RequestedDir = pw->pw_dir;
997 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1001 static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
1002 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
1003 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
1004 // macros defined in <unistd.h> on darwin >= 9
1005 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
1006 : _CS_DARWIN_USER_CACHE_DIR;
1007 size_t ConfLen = confstr(ConfName, nullptr, 0);
1010 Result.resize(ConfLen);
1011 ConfLen = confstr(ConfName, Result.data(), Result.size());
1012 } while (ConfLen > 0 && ConfLen != Result.size());
1015 assert(Result.back() == 0);
1026 static const char *getEnvTempDir() {
1027 // Check whether the temporary directory is specified by an environment
1029 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1030 for (const char *Env : EnvironmentVariables) {
1031 if (const char *Dir = std::getenv(Env))
1038 static const char *getDefaultTempDir(bool ErasedOnReboot) {
1049 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1052 if (ErasedOnReboot) {
1053 // There is no env variable for the cache directory.
1054 if (const char *RequestedDir = getEnvTempDir()) {
1055 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1060 if (getDarwinConfDir(ErasedOnReboot, Result))
1063 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1064 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1067 } // end namespace path
1069 } // end namespace sys
1070 } // end namespace llvm