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
40 #include <mach-o/dyld.h>
42 #if __has_include(<sys/clonefile.h>)
43 #include <sys/clonefile.h>
45 #elif defined(__FreeBSD__)
46 #include <osreldate.h>
47 #if __FreeBSD_version >= 1300057
50 #include <machine/elf.h>
51 extern char **environ;
53 #elif defined(__DragonFly__)
54 #include <sys/mount.h>
55 #elif defined(__MVS__)
56 #include "llvm/Support/AutoConvert.h"
60 // Both stdio.h and cstdio are included via different paths and
61 // stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
66 #if !defined(PATH_MAX)
70 #elif defined(__MVS__)
71 #define PATH_MAX _XOPEN_PATH_MAX
75 #include <sys/types.h>
76 #if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && \
77 !defined(__linux__) && !defined(__FreeBSD_kernel__) && !defined(_AIX)
78 #include <sys/statvfs.h>
79 #define STATVFS statvfs
80 #define FSTATVFS fstatvfs
81 #define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
83 #if defined(__OpenBSD__) || defined(__FreeBSD__)
84 #include <sys/mount.h>
85 #include <sys/param.h>
86 #elif defined(__linux__)
87 #if defined(HAVE_LINUX_MAGIC_H)
88 #include <linux/magic.h>
90 #if defined(HAVE_LINUX_NFS_FS_H)
91 #include <linux/nfs_fs.h>
93 #if defined(HAVE_LINUX_SMB_H)
94 #include <linux/smb.h>
99 #include <sys/statfs.h>
101 // <sys/vmount.h> depends on `uint` to be a typedef from <sys/types.h> to
102 // `uint_t`; however, <sys/types.h> does not always declare `uint`. We provide
103 // the typedef prior to including <sys/vmount.h> to work around this issue.
105 #include <sys/vmount.h>
107 #include <sys/mount.h>
109 #define STATVFS statfs
110 #define FSTATVFS fstatfs
111 #define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
114 #if defined(__NetBSD__) || defined(__DragonFly__) || defined(__GNU__) || \
116 #define STATVFS_F_FLAG(vfs) (vfs).f_flag
118 #define STATVFS_F_FLAG(vfs) (vfs).f_flags
121 using namespace llvm;
127 const file_t kInvalidFile = -1;
129 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
130 defined(__FreeBSD_kernel__) || defined(__linux__) || defined(__CYGWIN__) || \
131 defined(__DragonFly__) || defined(_AIX) || defined(__GNU__) || \
132 (defined(__sun__) && defined(__svr4__) || defined(__HAIKU__))
133 static int test_dir(char ret[PATH_MAX], const char *dir, const char *bin) {
135 char fullpath[PATH_MAX];
137 int chars = snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
138 // We cannot write PATH_MAX characters because the string will be terminated
139 // with a null character. Fail if truncation happened.
140 if (chars >= PATH_MAX)
142 if (!realpath(fullpath, ret))
144 if (stat(fullpath, &sb) != 0)
150 static char *getprogpath(char ret[PATH_MAX], const char *bin) {
154 /* First approach: absolute path. */
156 if (test_dir(ret, "/", bin) == 0)
161 /* Second approach: relative path. */
162 if (strchr(bin, '/')) {
164 if (!getcwd(cwd, PATH_MAX))
166 if (test_dir(ret, cwd, bin) == 0)
171 /* Third approach: $PATH */
173 if ((pv = getenv("PATH")) == nullptr)
175 char *s = strdup(pv);
179 for (char *t = strtok_r(s, ":", &state); t != nullptr;
180 t = strtok_r(nullptr, ":", &state)) {
181 if (test_dir(ret, t, bin) == 0) {
189 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
191 /// GetMainExecutable - Return the path to the main executable, given the
192 /// value of argv[0] from program startup.
193 std::string getMainExecutable(const char *argv0, void *MainAddr) {
194 #if defined(__APPLE__)
195 // On OS X the executable path is saved to the stack by dyld. Reading it
196 // from there is much faster than calling dladdr, especially for large
197 // binaries with symbols.
198 char exe_path[PATH_MAX];
199 uint32_t size = sizeof(exe_path);
200 if (_NSGetExecutablePath(exe_path, &size) == 0) {
201 char link_path[PATH_MAX];
202 if (realpath(exe_path, link_path))
205 #elif defined(__FreeBSD__)
206 // On FreeBSD if the exec path specified in ELF auxiliary vectors is
207 // preferred, if available. /proc/curproc/file and the KERN_PROC_PATHNAME
208 // sysctl may not return the desired path if there are multiple hardlinks
210 char exe_path[PATH_MAX];
211 #if __FreeBSD_version >= 1300057
212 if (elf_aux_info(AT_EXECPATH, exe_path, sizeof(exe_path)) == 0) {
213 char link_path[PATH_MAX];
214 if (realpath(exe_path, link_path))
218 // elf_aux_info(AT_EXECPATH, ... is not available in all supported versions,
219 // fall back to finding the ELF auxiliary vectors after the process's
221 char **p = ::environ;
224 // Iterate through auxiliary vectors for AT_EXECPATH.
225 for (Elf_Auxinfo *aux = (Elf_Auxinfo *)p; aux->a_type != AT_NULL; aux++) {
226 if (aux->a_type == AT_EXECPATH) {
227 char link_path[PATH_MAX];
228 if (realpath((char *)aux->a_un.a_ptr, link_path))
233 // Fall back to argv[0] if auxiliary vectors are not available.
234 if (getprogpath(exe_path, argv0) != NULL)
236 #elif defined(_AIX) || defined(__DragonFly__) || defined(__FreeBSD_kernel__) || \
238 const char *curproc = "/proc/curproc/file";
239 char exe_path[PATH_MAX];
240 if (sys::fs::exists(curproc)) {
241 ssize_t len = readlink(curproc, exe_path, sizeof(exe_path));
243 // Null terminate the string for realpath. readlink never null
244 // terminates its output.
245 len = std::min(len, ssize_t(sizeof(exe_path) - 1));
246 exe_path[len] = '\0';
250 // If we don't have procfs mounted, fall back to argv[0]
251 if (getprogpath(exe_path, argv0) != NULL)
253 #elif defined(__linux__) || defined(__CYGWIN__) || defined(__gnu_hurd__)
254 char exe_path[PATH_MAX];
255 const char *aPath = "/proc/self/exe";
256 if (sys::fs::exists(aPath)) {
257 // /proc is not always mounted under Linux (chroot for example).
258 ssize_t len = readlink(aPath, exe_path, sizeof(exe_path));
262 // Null terminate the string for realpath. readlink never null
263 // terminates its output.
264 len = std::min(len, ssize_t(sizeof(exe_path) - 1));
265 exe_path[len] = '\0';
267 // On Linux, /proc/self/exe always looks through symlinks. However, on
268 // GNU/Hurd, /proc/self/exe is a symlink to the path that was used to start
269 // the program, and not the eventual binary file. Therefore, call realpath
270 // so this behaves the same on all platforms.
271 #if _POSIX_VERSION >= 200112 || defined(__GLIBC__)
272 if (char *real_path = realpath(exe_path, nullptr)) {
273 std::string ret = std::string(real_path);
278 char real_path[PATH_MAX];
279 if (realpath(exe_path, real_path))
280 return std::string(real_path);
283 // Fall back to the classical detection.
284 if (getprogpath(exe_path, argv0))
286 #elif defined(__OpenBSD__) || defined(__HAIKU__)
287 char exe_path[PATH_MAX];
289 if (getprogpath(exe_path, argv0) != NULL)
291 #elif defined(__sun__) && defined(__svr4__)
292 char exe_path[PATH_MAX];
293 const char *aPath = "/proc/self/execname";
294 if (sys::fs::exists(aPath)) {
295 int fd = open(aPath, O_RDONLY);
298 if (read(fd, exe_path, sizeof(exe_path)) < 0)
302 // Fall back to the classical detection.
303 if (getprogpath(exe_path, argv0) != NULL)
305 #elif defined(__MVS__)
308 char exe_path[PS_PATHBLEN];
309 pid_t pid = getpid();
311 memset(&buf, 0, sizeof(buf));
312 buf.ps_pathptr = exe_path;
313 buf.ps_pathlen = sizeof(exe_path);
316 if ((token = w_getpsent(token, &buf, sizeof(buf))) <= 0)
318 if (buf.ps_pid != pid)
320 char real_path[PATH_MAX];
321 if (realpath(exe_path, real_path))
322 return std::string(real_path);
323 break; // Found entry, but realpath failed.
325 #elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
326 // Use dladdr to get executable path if available.
328 int err = dladdr(MainAddr, &DLInfo);
332 // If the filename is a symlink, we need to resolve and return the location of
333 // the actual executable.
334 char link_path[PATH_MAX];
335 if (realpath(DLInfo.dli_fname, link_path))
338 #error GetMainExecutable is not implemented on this host yet.
343 TimePoint<> basic_file_status::getLastAccessedTime() const {
344 return toTimePoint(fs_st_atime, fs_st_atime_nsec);
347 TimePoint<> basic_file_status::getLastModificationTime() const {
348 return toTimePoint(fs_st_mtime, fs_st_mtime_nsec);
351 UniqueID file_status::getUniqueID() const {
352 return UniqueID(fs_st_dev, fs_st_ino);
355 uint32_t file_status::getLinkCount() const { return fs_st_nlinks; }
357 ErrorOr<space_info> disk_space(const Twine &Path) {
359 if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
360 return errnoAsErrorCode();
361 auto FrSize = STATVFS_F_FRSIZE(Vfs);
362 space_info SpaceInfo;
363 SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
364 SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
365 SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
369 std::error_code current_path(SmallVectorImpl<char> &result) {
372 const char *pwd = ::getenv("PWD");
373 llvm::sys::fs::file_status PWDStatus, DotStatus;
374 if (pwd && llvm::sys::path::is_absolute(pwd) &&
375 !llvm::sys::fs::status(pwd, PWDStatus) &&
376 !llvm::sys::fs::status(".", DotStatus) &&
377 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
378 result.append(pwd, pwd + strlen(pwd));
379 return std::error_code();
382 result.resize_for_overwrite(PATH_MAX);
385 if (::getcwd(result.data(), result.size()) == nullptr) {
386 // See if there was a real error.
387 if (errno != ENOMEM) {
389 return errnoAsErrorCode();
391 // Otherwise there just wasn't enough space.
392 result.resize_for_overwrite(result.capacity() * 2);
397 result.truncate(strlen(result.data()));
398 return std::error_code();
401 std::error_code set_current_path(const Twine &path) {
402 SmallString<128> path_storage;
403 StringRef p = path.toNullTerminatedStringRef(path_storage);
405 if (::chdir(p.begin()) == -1)
406 return errnoAsErrorCode();
408 return std::error_code();
411 std::error_code create_directory(const Twine &path, bool IgnoreExisting,
413 SmallString<128> path_storage;
414 StringRef p = path.toNullTerminatedStringRef(path_storage);
416 if (::mkdir(p.begin(), Perms) == -1) {
417 if (errno != EEXIST || !IgnoreExisting)
418 return errnoAsErrorCode();
421 return std::error_code();
424 // Note that we are using symbolic link because hard links are not supported by
425 // all filesystems (SMB doesn't).
426 std::error_code create_link(const Twine &to, const Twine &from) {
428 SmallString<128> from_storage;
429 SmallString<128> to_storage;
430 StringRef f = from.toNullTerminatedStringRef(from_storage);
431 StringRef t = to.toNullTerminatedStringRef(to_storage);
433 if (::symlink(t.begin(), f.begin()) == -1)
434 return errnoAsErrorCode();
436 return std::error_code();
439 std::error_code create_hard_link(const Twine &to, const Twine &from) {
441 SmallString<128> from_storage;
442 SmallString<128> to_storage;
443 StringRef f = from.toNullTerminatedStringRef(from_storage);
444 StringRef t = to.toNullTerminatedStringRef(to_storage);
446 if (::link(t.begin(), f.begin()) == -1)
447 return errnoAsErrorCode();
449 return std::error_code();
452 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
453 SmallString<128> path_storage;
454 StringRef p = path.toNullTerminatedStringRef(path_storage);
457 if (lstat(p.begin(), &buf) != 0) {
458 if (errno != ENOENT || !IgnoreNonExisting)
459 return errnoAsErrorCode();
460 return std::error_code();
463 // Note: this check catches strange situations. In all cases, LLVM should
464 // only be involved in the creation and deletion of regular files. This
465 // check ensures that what we're trying to erase is a regular file. It
466 // effectively prevents LLVM from erasing things like /dev/null, any block
467 // special file, or other things that aren't "regular" files.
468 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
469 return make_error_code(errc::operation_not_permitted);
471 if (::remove(p.begin()) == -1) {
472 if (errno != ENOENT || !IgnoreNonExisting)
473 return errnoAsErrorCode();
476 return std::error_code();
479 static bool is_local_impl(struct STATVFS &Vfs) {
480 #if defined(__linux__) || defined(__GNU__)
481 #ifndef NFS_SUPER_MAGIC
482 #define NFS_SUPER_MAGIC 0x6969
484 #ifndef SMB_SUPER_MAGIC
485 #define SMB_SUPER_MAGIC 0x517B
487 #ifndef CIFS_MAGIC_NUMBER
488 #define CIFS_MAGIC_NUMBER 0xFF534D42
490 #if defined(__GNU__) && ((__GLIBC__ < 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ < 39)))
491 switch ((uint32_t)Vfs.__f_type) {
493 switch ((uint32_t)Vfs.f_type) {
495 case NFS_SUPER_MAGIC:
496 case SMB_SUPER_MAGIC:
497 case CIFS_MAGIC_NUMBER:
502 #elif defined(__CYGWIN__)
503 // Cygwin doesn't expose this information; would need to use Win32 API.
505 #elif defined(__Fuchsia__)
506 // Fuchsia doesn't yet support remote filesystem mounts.
508 #elif defined(__EMSCRIPTEN__)
509 // Emscripten doesn't currently support remote filesystem mounts.
511 #elif defined(__HAIKU__)
512 // Haiku doesn't expose this information.
515 // statvfs::f_basetype contains a null-terminated FSType name of the mounted
517 StringRef fstype(Vfs.f_basetype);
518 // NFS is the only non-local fstype??
519 return fstype != "nfs";
521 // Call mntctl; try more than twice in case of timing issues with a concurrent
524 size_t BufSize = 2048u;
525 std::unique_ptr<char[]> Buf;
528 Buf = std::make_unique<char[]>(BufSize);
529 Ret = mntctl(MCTL_QUERY, BufSize, Buf.get());
532 BufSize = *reinterpret_cast<unsigned int *>(Buf.get());
537 // There was an error; "remote" is the conservative answer.
540 // Look for the correct vmount entry.
541 char *CurObjPtr = Buf.get();
543 struct vmount *Vp = reinterpret_cast<struct vmount *>(CurObjPtr);
544 static_assert(sizeof(Vfs.f_fsid) == sizeof(Vp->vmt_fsid),
545 "fsid length mismatch");
546 if (memcmp(&Vfs.f_fsid, &Vp->vmt_fsid, sizeof Vfs.f_fsid) == 0)
547 return (Vp->vmt_flags & MNT_REMOTE) == 0;
549 CurObjPtr += Vp->vmt_length;
552 // vmount entry not found; "remote" is the conservative answer.
554 #elif defined(__MVS__)
555 // The file system can have an arbitrary structure on z/OS; must go with the
556 // conservative answer.
559 return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
563 std::error_code is_local(const Twine &Path, bool &Result) {
565 if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
566 return errnoAsErrorCode();
568 Result = is_local_impl(Vfs);
569 return std::error_code();
572 std::error_code is_local(int FD, bool &Result) {
574 if (::FSTATVFS(FD, &Vfs))
575 return errnoAsErrorCode();
577 Result = is_local_impl(Vfs);
578 return std::error_code();
581 std::error_code rename(const Twine &from, const Twine &to) {
583 SmallString<128> from_storage;
584 SmallString<128> to_storage;
585 StringRef f = from.toNullTerminatedStringRef(from_storage);
586 StringRef t = to.toNullTerminatedStringRef(to_storage);
588 if (::rename(f.begin(), t.begin()) == -1)
589 return errnoAsErrorCode();
591 return std::error_code();
594 std::error_code resize_file(int FD, uint64_t Size) {
595 // Use ftruncate as a fallback. It may or may not allocate space. At least on
596 // OS X with HFS+ it does.
597 if (::ftruncate(FD, Size) == -1)
598 return errnoAsErrorCode();
600 return std::error_code();
603 static int convertAccessMode(AccessMode Mode) {
605 case AccessMode::Exist:
607 case AccessMode::Write:
609 case AccessMode::Execute:
610 return R_OK | X_OK; // scripts also need R_OK.
612 llvm_unreachable("invalid enum");
615 std::error_code access(const Twine &Path, AccessMode Mode) {
616 SmallString<128> PathStorage;
617 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
619 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
620 return errnoAsErrorCode();
622 if (Mode == AccessMode::Execute) {
623 // Don't say that directories are executable.
625 if (0 != stat(P.begin(), &buf))
626 return errc::permission_denied;
627 if (!S_ISREG(buf.st_mode))
628 return errc::permission_denied;
631 return std::error_code();
634 bool can_execute(const Twine &Path) {
635 return !access(Path, AccessMode::Execute);
638 bool equivalent(file_status A, file_status B) {
639 assert(status_known(A) && status_known(B));
640 return A.fs_st_dev == B.fs_st_dev && A.fs_st_ino == B.fs_st_ino;
643 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
644 file_status fsA, fsB;
645 if (std::error_code ec = status(A, fsA))
647 if (std::error_code ec = status(B, fsB))
649 result = equivalent(fsA, fsB);
650 return std::error_code();
653 static void expandTildeExpr(SmallVectorImpl<char> &Path) {
654 StringRef PathStr(Path.begin(), Path.size());
655 if (PathStr.empty() || !PathStr.starts_with("~"))
658 PathStr = PathStr.drop_front();
660 PathStr.take_until([](char c) { return path::is_separator(c); });
661 StringRef Remainder = PathStr.substr(Expr.size() + 1);
662 SmallString<128> Storage;
664 // This is just ~/..., resolve it to the current user's home dir.
665 if (!path::home_directory(Storage)) {
666 // For some reason we couldn't get the home directory. Just exit.
670 // Overwrite the first character and insert the rest.
671 Path[0] = Storage[0];
672 Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
676 // This is a string of the form ~username/, look up this user's entry in the
677 // password database.
678 std::unique_ptr<char[]> Buf;
679 long BufSize = sysconf(_SC_GETPW_R_SIZE_MAX);
682 Buf = std::make_unique<char[]>(BufSize);
684 std::string User = Expr.str();
685 struct passwd *Entry = nullptr;
686 getpwnam_r(User.c_str(), &Pwd, Buf.get(), BufSize, &Entry);
688 if (!Entry || !Entry->pw_dir) {
689 // Unable to look up the entry, just return back the original path.
695 Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
696 llvm::sys::path::append(Path, Storage);
699 void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
701 if (path.isTriviallyEmpty())
705 expandTildeExpr(dest);
708 static file_type typeForMode(mode_t Mode) {
710 return file_type::directory_file;
711 else if (S_ISREG(Mode))
712 return file_type::regular_file;
713 else if (S_ISBLK(Mode))
714 return file_type::block_file;
715 else if (S_ISCHR(Mode))
716 return file_type::character_file;
717 else if (S_ISFIFO(Mode))
718 return file_type::fifo_file;
719 else if (S_ISSOCK(Mode))
720 return file_type::socket_file;
721 else if (S_ISLNK(Mode))
722 return file_type::symlink_file;
723 return file_type::type_unknown;
726 static std::error_code fillStatus(int StatRet, const struct stat &Status,
727 file_status &Result) {
729 std::error_code EC = errnoAsErrorCode();
730 if (EC == errc::no_such_file_or_directory)
731 Result = file_status(file_type::file_not_found);
733 Result = file_status(file_type::status_error);
737 uint32_t atime_nsec, mtime_nsec;
738 #if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
739 atime_nsec = Status.st_atimespec.tv_nsec;
740 mtime_nsec = Status.st_mtimespec.tv_nsec;
741 #elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
742 atime_nsec = Status.st_atim.tv_nsec;
743 mtime_nsec = Status.st_mtim.tv_nsec;
745 atime_nsec = mtime_nsec = 0;
748 perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
749 Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev,
750 Status.st_nlink, Status.st_ino, Status.st_atime,
751 atime_nsec, Status.st_mtime, mtime_nsec, Status.st_uid,
752 Status.st_gid, Status.st_size);
754 return std::error_code();
757 std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
758 SmallString<128> PathStorage;
759 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
762 int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
763 return fillStatus(StatRet, Status, Result);
766 std::error_code status(int FD, file_status &Result) {
768 int StatRet = ::fstat(FD, &Status);
769 return fillStatus(StatRet, Status, Result);
772 unsigned getUmask() {
773 // Chose arbitary new mask and reset the umask to the old mask.
774 // umask(2) never fails so ignore the return of the second call.
775 unsigned Mask = ::umask(0);
780 std::error_code setPermissions(const Twine &Path, perms Permissions) {
781 SmallString<128> PathStorage;
782 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
784 if (::chmod(P.begin(), Permissions))
785 return errnoAsErrorCode();
786 return std::error_code();
789 std::error_code setPermissions(int FD, perms Permissions) {
790 if (::fchmod(FD, Permissions))
791 return errnoAsErrorCode();
792 return std::error_code();
795 std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
796 TimePoint<> ModificationTime) {
797 #if defined(HAVE_FUTIMENS)
799 Times[0] = sys::toTimeSpec(AccessTime);
800 Times[1] = sys::toTimeSpec(ModificationTime);
801 if (::futimens(FD, Times))
802 return errnoAsErrorCode();
803 return std::error_code();
804 #elif defined(HAVE_FUTIMES)
806 Times[0] = sys::toTimeVal(
807 std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
809 sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
811 if (::futimes(FD, Times))
812 return errnoAsErrorCode();
813 return std::error_code();
814 #elif defined(__MVS__)
816 memset(&Attr, 0, sizeof(Attr));
817 Attr.att_atimechg = 1;
818 Attr.att_atime = sys::toTimeT(AccessTime);
819 Attr.att_mtimechg = 1;
820 Attr.att_mtime = sys::toTimeT(ModificationTime);
821 if (::__fchattr(FD, &Attr, sizeof(Attr)) != 0)
822 return errnoAsErrorCode();
823 return std::error_code();
825 #warning Missing futimes() and futimens()
826 return make_error_code(errc::function_not_supported);
830 std::error_code mapped_file_region::init(int FD, uint64_t Offset,
834 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
835 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
836 #if defined(MAP_NORESERVE)
837 flags |= MAP_NORESERVE;
839 #if defined(__APPLE__)
840 //----------------------------------------------------------------------
841 // Newer versions of MacOSX have a flag that will allow us to read from
842 // binaries whose code signature is invalid without crashing by using
843 // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
844 // is mapped we can avoid crashing and return zeroes to any pages we try
845 // to read if the media becomes unavailable by using the
846 // MAP_RESILIENT_MEDIA flag. These flags are only usable when mapping
847 // with PROT_READ, so take care not to specify them otherwise.
848 //----------------------------------------------------------------------
849 if (Mode == readonly) {
850 #if defined(MAP_RESILIENT_CODESIGN)
851 flags |= MAP_RESILIENT_CODESIGN;
853 #if defined(MAP_RESILIENT_MEDIA)
854 flags |= MAP_RESILIENT_MEDIA;
857 #endif // #if defined (__APPLE__)
859 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
860 if (Mapping == MAP_FAILED)
861 return errnoAsErrorCode();
862 return std::error_code();
865 mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
866 uint64_t offset, std::error_code &ec)
867 : Size(length), Mode(mode) {
869 ec = init(fd, offset, mode);
871 copyFrom(mapped_file_region());
874 void mapped_file_region::unmapImpl() {
876 ::munmap(Mapping, Size);
879 void mapped_file_region::dontNeedImpl() {
880 assert(Mode == mapped_file_region::readonly);
883 #if defined(__MVS__) || defined(_AIX)
884 // If we don't have madvise, or it isn't beneficial, treat this as a no-op.
885 #elif defined(POSIX_MADV_DONTNEED)
886 ::posix_madvise(Mapping, Size, POSIX_MADV_DONTNEED);
888 ::madvise(Mapping, Size, MADV_DONTNEED);
892 int mapped_file_region::alignment() { return Process::getPageSizeEstimate(); }
894 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
896 bool follow_symlinks) {
897 SmallString<128> path_null(path);
898 DIR *directory = ::opendir(path_null.c_str());
900 return errnoAsErrorCode();
902 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
903 // Add something for replace_filename to replace.
904 path::append(path_null, ".");
905 it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
906 return directory_iterator_increment(it);
909 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
910 if (it.IterationHandle)
911 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
912 it.IterationHandle = 0;
913 it.CurrentEntry = directory_entry();
914 return std::error_code();
917 static file_type direntType(dirent *Entry) {
918 // Most platforms provide the file type in the dirent: Linux/BSD/Mac.
919 // The DTTOIF macro lets us reuse our status -> type conversion.
920 // Note that while glibc provides a macro to see if this is supported,
921 // _DIRENT_HAVE_D_TYPE, it's not defined on BSD/Mac, so we test for the
922 // d_type-to-mode_t conversion macro instead.
924 return typeForMode(DTTOIF(Entry->d_type));
926 // Other platforms such as Solaris require a stat() to get the type.
927 return file_type::type_unknown;
931 std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
933 dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));
934 if (CurDir == nullptr && errno != 0) {
935 return errnoAsErrorCode();
936 } else if (CurDir != nullptr) {
937 StringRef Name(CurDir->d_name);
938 if ((Name.size() == 1 && Name[0] == '.') ||
939 (Name.size() == 2 && Name[0] == '.' && Name[1] == '.'))
940 return directory_iterator_increment(It);
941 It.CurrentEntry.replace_filename(Name, direntType(CurDir));
943 return directory_iterator_destruct(It);
945 return std::error_code();
948 ErrorOr<basic_file_status> directory_entry::status() const {
950 if (auto EC = fs::status(Path, s, FollowSymlinks))
956 // FreeBSD optionally provides /proc/self/fd, but it is incompatible with
957 // Linux. The thing to use is realpath.
959 #if !defined(__FreeBSD__) && !defined(__OpenBSD__)
960 #define TRY_PROC_SELF_FD
963 #if !defined(F_GETPATH) && defined(TRY_PROC_SELF_FD)
964 static bool hasProcSelfFD() {
965 // If we have a /proc filesystem mounted, we can quickly establish the
966 // real name of the file with readlink
967 static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
972 static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
975 if (Access == FA_Read)
977 else if (Access == FA_Write)
979 else if (Access == (FA_Read | FA_Write))
982 // This is for compatibility with old code that assumed OF_Append implied
983 // would open an existing file. See Windows/Path.inc for a longer comment.
984 if (Flags & OF_Append)
985 Disp = CD_OpenAlways;
987 if (Disp == CD_CreateNew) {
988 Result |= O_CREAT; // Create if it doesn't exist.
989 Result |= O_EXCL; // Fail if it does.
990 } else if (Disp == CD_CreateAlways) {
991 Result |= O_CREAT; // Create if it doesn't exist.
992 Result |= O_TRUNC; // Truncate if it does.
993 } else if (Disp == CD_OpenAlways) {
994 Result |= O_CREAT; // Create if it doesn't exist.
995 } else if (Disp == CD_OpenExisting) {
996 // Nothing special, just don't add O_CREAT and we get these semantics.
999 // Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
1000 // calling write(). Instead we need to use lseek() to set offset to EOF after
1003 if (Flags & OF_Append)
1008 if (!(Flags & OF_ChildInherit))
1009 Result |= O_CLOEXEC;
1015 std::error_code openFile(const Twine &Name, int &ResultFD,
1016 CreationDisposition Disp, FileAccess Access,
1017 OpenFlags Flags, unsigned Mode) {
1018 int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
1020 SmallString<128> Storage;
1021 StringRef P = Name.toNullTerminatedStringRef(Storage);
1022 // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
1023 // when open is overloaded, such as in Bionic.
1024 auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
1025 if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
1026 return errnoAsErrorCode();
1028 if (!(Flags & OF_ChildInherit)) {
1029 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
1031 assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
1036 /* Reason about auto-conversion and file tags. Setting the file tag only
1037 * applies if file is opened in write mode:
1040 * File exists File created
1041 * CD_CreateNew n/a conv: on
1043 * CD_CreateAlways conv: auto conv: on
1044 * tag: auto 1047 tag: set 1047
1045 * CD_OpenAlways conv: auto conv: on
1046 * tag: auto 1047 tag: set 1047
1047 * CD_OpenExisting conv: auto n/a
1051 * File exists File created
1052 * CD_CreateNew n/a conv: off
1054 * CD_CreateAlways conv: off conv: off
1055 * tag: auto binary tag: set binary
1056 * CD_OpenAlways conv: off conv: off
1057 * tag: auto binary tag: set binary
1058 * CD_OpenExisting conv: off n/a
1062 * conv: off -> auto-conversion is turned off
1063 * conv: on -> auto-conversion is turned on
1064 * conv: auto -> auto-conversion is turned on if the file is untagged
1065 * tag: set 1047 -> set the file tag to text encoded in 1047
1066 * tag: set binary -> set the file tag to binary
1067 * tag: auto 1047 -> set file tag to 1047 if not set
1068 * tag: auto binary -> set file tag to binary if not set
1069 * tag: unchanged -> do not care about the file tag
1071 * It is not possible to distinguish between the cases "file exists" and
1072 * "file created". In the latter case, the file tag is not set and the file
1073 * size is zero. The decision table boils down to:
1075 * the file tag is set if
1076 * - the file is opened for writing
1077 * - the create disposition is not equal to CD_OpenExisting
1078 * - the file tag is not set
1079 * - the file size is zero
1081 * This only applies if the file is a regular file. E.g. enabling
1082 * auto-conversion for reading from /dev/null results in error EINVAL when
1085 * Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
1086 * calling write(). Instead we need to use lseek() to set offset to EOF after
1089 if ((Flags & OF_Append) && lseek(ResultFD, 0, SEEK_END) == -1)
1090 return errnoAsErrorCode();
1092 if (fstat(ResultFD, &Stat) == -1)
1093 return errnoAsErrorCode();
1094 if (S_ISREG(Stat.st_mode)) {
1095 bool DoSetTag = (Access & FA_Write) && (Disp != CD_OpenExisting) &&
1096 !Stat.st_tag.ft_txtflag && !Stat.st_tag.ft_ccsid &&
1098 if (Flags & OF_Text) {
1099 if (auto EC = llvm::enablezOSAutoConversion(ResultFD))
1102 if (auto EC = llvm::setzOSFileTag(ResultFD, CCSID_IBM_1047, true))
1106 if (auto EC = llvm::disablezOSAutoConversion(ResultFD))
1109 if (auto EC = llvm::setzOSFileTag(ResultFD, FT_BINARY, false))
1116 return std::error_code();
1119 Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,
1120 FileAccess Access, OpenFlags Flags,
1124 std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
1126 return errorCodeToError(EC);
1130 std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1132 SmallVectorImpl<char> *RealPath) {
1133 std::error_code EC =
1134 openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
1138 // Attempt to get the real name of the file, if the user asked
1140 return std::error_code();
1142 #if defined(F_GETPATH)
1143 // When F_GETPATH is availble, it is the quickest way to get
1144 // the real path name.
1145 char Buffer[PATH_MAX];
1146 if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
1147 RealPath->append(Buffer, Buffer + strlen(Buffer));
1149 char Buffer[PATH_MAX];
1150 #if defined(TRY_PROC_SELF_FD)
1151 if (hasProcSelfFD()) {
1153 snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
1154 ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
1156 RealPath->append(Buffer, Buffer + CharCount);
1159 SmallString<128> Storage;
1160 StringRef P = Name.toNullTerminatedStringRef(Storage);
1162 // Use ::realpath to get the real path name
1163 if (::realpath(P.begin(), Buffer) != nullptr)
1164 RealPath->append(Buffer, Buffer + strlen(Buffer));
1165 #if defined(TRY_PROC_SELF_FD)
1169 return std::error_code();
1172 Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1173 SmallVectorImpl<char> *RealPath) {
1175 std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
1177 return errorCodeToError(EC);
1181 file_t getStdinHandle() { return 0; }
1182 file_t getStdoutHandle() { return 1; }
1183 file_t getStderrHandle() { return 2; }
1185 Expected<size_t> readNativeFile(file_t FD, MutableArrayRef<char> Buf) {
1186 #if defined(__APPLE__)
1187 size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
1189 size_t Size = Buf.size();
1191 ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
1192 if (ssize_t(NumRead) == -1)
1193 return errorCodeToError(errnoAsErrorCode());
1194 // The underlying operation on these platforms allow opening directories
1195 // for reading in more cases than other platforms.
1196 #if defined(__MVS__) || defined(_AIX)
1198 if (fstat(FD, &Status) == -1)
1199 return errorCodeToError(errnoAsErrorCode());
1200 if (S_ISDIR(Status.st_mode))
1201 return errorCodeToError(make_error_code(errc::is_a_directory));
1206 Expected<size_t> readNativeFileSlice(file_t FD, MutableArrayRef<char> Buf,
1208 #if defined(__APPLE__)
1209 size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
1211 size_t Size = Buf.size();
1215 sys::RetryAfterSignal(-1, ::pread, FD, Buf.data(), Size, Offset);
1217 if (lseek(FD, Offset, SEEK_SET) == -1)
1218 return errorCodeToError(errnoAsErrorCode());
1219 ssize_t NumRead = sys::RetryAfterSignal(-1, ::read, FD, Buf.data(), Size);
1222 return errorCodeToError(errnoAsErrorCode());
1226 std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout) {
1227 auto Start = std::chrono::steady_clock::now();
1228 auto End = Start + Timeout;
1231 memset(&Lock, 0, sizeof(Lock));
1232 Lock.l_type = F_WRLCK;
1233 Lock.l_whence = SEEK_SET;
1236 if (::fcntl(FD, F_SETLK, &Lock) != -1)
1237 return std::error_code();
1239 if (Error != EACCES && Error != EAGAIN)
1240 return std::error_code(Error, std::generic_category());
1242 } while (std::chrono::steady_clock::now() < End);
1243 return make_error_code(errc::no_lock_available);
1246 std::error_code lockFile(int FD) {
1248 memset(&Lock, 0, sizeof(Lock));
1249 Lock.l_type = F_WRLCK;
1250 Lock.l_whence = SEEK_SET;
1253 if (::fcntl(FD, F_SETLKW, &Lock) != -1)
1254 return std::error_code();
1255 return errnoAsErrorCode();
1258 std::error_code unlockFile(int FD) {
1260 Lock.l_type = F_UNLCK;
1261 Lock.l_whence = SEEK_SET;
1264 if (::fcntl(FD, F_SETLK, &Lock) != -1)
1265 return std::error_code();
1266 return errnoAsErrorCode();
1269 std::error_code closeFile(file_t &F) {
1272 return Process::SafelyCloseFileDescriptor(TmpF);
1275 template <typename T>
1276 static std::error_code remove_directories_impl(const T &Entry,
1277 bool IgnoreErrors) {
1279 directory_iterator Begin(Entry, EC, false);
1280 directory_iterator End;
1281 while (Begin != End) {
1282 auto &Item = *Begin;
1283 ErrorOr<basic_file_status> st = Item.status();
1285 if (is_directory(*st)) {
1286 EC = remove_directories_impl(Item, IgnoreErrors);
1287 if (EC && !IgnoreErrors)
1291 EC = fs::remove(Item.path(), true);
1292 if (EC && !IgnoreErrors)
1294 } else if (!IgnoreErrors) {
1295 return st.getError();
1298 Begin.increment(EC);
1299 if (EC && !IgnoreErrors)
1302 return std::error_code();
1305 std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1306 auto EC = remove_directories_impl(path, IgnoreErrors);
1307 if (EC && !IgnoreErrors)
1309 EC = fs::remove(path, true);
1310 if (EC && !IgnoreErrors)
1312 return std::error_code();
1315 std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1316 bool expand_tilde) {
1318 if (path.isTriviallyEmpty())
1319 return std::error_code();
1322 SmallString<128> Storage;
1323 path.toVector(Storage);
1324 expandTildeExpr(Storage);
1325 return real_path(Storage, dest, false);
1328 SmallString<128> Storage;
1329 StringRef P = path.toNullTerminatedStringRef(Storage);
1330 char Buffer[PATH_MAX];
1331 if (::realpath(P.begin(), Buffer) == nullptr)
1332 return errnoAsErrorCode();
1333 dest.append(Buffer, Buffer + strlen(Buffer));
1334 return std::error_code();
1337 std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group) {
1338 auto FChown = [&]() { return ::fchown(FD, Owner, Group); };
1339 // Retry if fchown call fails due to interruption.
1340 if ((sys::RetryAfterSignal(-1, FChown)) < 0)
1341 return errnoAsErrorCode();
1342 return std::error_code();
1345 } // end namespace fs
1349 bool home_directory(SmallVectorImpl<char> &result) {
1350 std::unique_ptr<char[]> Buf;
1351 char *RequestedDir = getenv("HOME");
1352 if (!RequestedDir) {
1353 long BufSize = sysconf(_SC_GETPW_R_SIZE_MAX);
1356 Buf = std::make_unique<char[]>(BufSize);
1358 struct passwd *pw = nullptr;
1359 getpwuid_r(getuid(), &Pwd, Buf.get(), BufSize, &pw);
1360 if (pw && pw->pw_dir)
1361 RequestedDir = pw->pw_dir;
1367 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1371 static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
1372 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
1373 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
1374 // macros defined in <unistd.h> on darwin >= 9
1375 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR : _CS_DARWIN_USER_CACHE_DIR;
1376 size_t ConfLen = confstr(ConfName, nullptr, 0);
1379 Result.resize(ConfLen);
1380 ConfLen = confstr(ConfName, Result.data(), Result.size());
1381 } while (ConfLen > 0 && ConfLen != Result.size());
1384 assert(Result.back() == 0);
1395 bool user_config_directory(SmallVectorImpl<char> &result) {
1397 // Mac: ~/Library/Preferences/
1398 if (home_directory(result)) {
1399 append(result, "Library", "Preferences");
1403 // XDG_CONFIG_HOME as defined in the XDG Base Directory Specification:
1404 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1405 if (const char *RequestedDir = getenv("XDG_CONFIG_HOME")) {
1407 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1411 // Fallback: ~/.config
1412 if (!home_directory(result)) {
1415 append(result, ".config");
1419 bool cache_directory(SmallVectorImpl<char> &result) {
1421 if (getDarwinConfDir(false /*tempDir*/, result)) {
1425 // XDG_CACHE_HOME as defined in the XDG Base Directory Specification:
1426 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1427 if (const char *RequestedDir = getenv("XDG_CACHE_HOME")) {
1429 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1433 if (!home_directory(result)) {
1436 append(result, ".cache");
1440 static const char *getEnvTempDir() {
1441 // Check whether the temporary directory is specified by an environment
1443 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1444 for (const char *Env : EnvironmentVariables) {
1445 if (const char *Dir = std::getenv(Env))
1452 static const char *getDefaultTempDir(bool ErasedOnReboot) {
1463 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1466 if (ErasedOnReboot) {
1467 // There is no env variable for the cache directory.
1468 if (const char *RequestedDir = getEnvTempDir()) {
1469 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1474 if (getDarwinConfDir(ErasedOnReboot, Result))
1477 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1478 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1481 } // end namespace path
1486 /// This implementation tries to perform an APFS CoW clone of the file,
1487 /// which can be much faster and uses less space.
1488 /// Unfortunately fcopyfile(3) does not support COPYFILE_CLONE, so the
1489 /// file descriptor variant of this function still uses the default
1491 std::error_code copy_file(const Twine &From, const Twine &To) {
1492 std::string FromS = From.str();
1493 std::string ToS = To.str();
1494 #if __has_builtin(__builtin_available)
1495 if (__builtin_available(macos 10.12, *)) {
1496 // Optimistically try to use clonefile() and handle errors, rather than
1497 // calling stat() to see if it'll work.
1499 // Note: It's okay if From is a symlink. In contrast to the behaviour of
1500 // copyfile() with COPYFILE_CLONE, clonefile() clones targets (not the
1501 // symlink itself) unless the flag CLONE_NOFOLLOW is passed.
1502 if (!clonefile(FromS.c_str(), ToS.c_str(), 0))
1503 return std::error_code();
1507 case EEXIST: // To already exists.
1508 case ENOTSUP: // Device does not support cloning.
1509 case EXDEV: // From and To are on different devices.
1512 // Anything else will also break copyfile().
1513 return std::error_code(Errno, std::generic_category());
1516 // TODO: For EEXIST, profile calling fs::generateUniqueName() and
1517 // clonefile() in a retry loop (then rename() on success) before falling
1518 // back to copyfile(). Depending on the size of the file this could be
1522 if (!copyfile(FromS.c_str(), ToS.c_str(), /*State=*/NULL, COPYFILE_DATA))
1523 return std::error_code();
1524 return errnoAsErrorCode();
1528 } // end namespace fs
1530 } // end namespace sys
1531 } // end namespace llvm