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
39 #include <mach-o/dyld.h>
41 #elif defined(__DragonFly__)
42 #include <sys/mount.h>
45 // Both stdio.h and cstdio are included via different paths and
46 // stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
52 #if defined(__GNU__) && !defined(PATH_MAX)
53 # define PATH_MAX 4096
54 # define MAXPATHLEN 4096
57 #include <sys/types.h>
58 #if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && \
59 !defined(__linux__) && !defined(__FreeBSD_kernel__)
60 #include <sys/statvfs.h>
61 #define STATVFS statvfs
62 #define FSTATVFS fstatvfs
63 #define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
65 #if defined(__OpenBSD__) || defined(__FreeBSD__)
66 #include <sys/mount.h>
67 #include <sys/param.h>
68 #elif defined(__linux__)
69 #if defined(HAVE_LINUX_MAGIC_H)
70 #include <linux/magic.h>
72 #if defined(HAVE_LINUX_NFS_FS_H)
73 #include <linux/nfs_fs.h>
75 #if defined(HAVE_LINUX_SMB_H)
76 #include <linux/smb.h>
81 #include <sys/mount.h>
83 #define STATVFS statfs
84 #define FSTATVFS fstatfs
85 #define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
88 #if defined(__NetBSD__) || defined(__DragonFly__) || defined(__GNU__)
89 #define STATVFS_F_FLAG(vfs) (vfs).f_flag
91 #define STATVFS_F_FLAG(vfs) (vfs).f_flags
100 const file_t kInvalidFile = -1;
102 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
103 defined(__minix) || defined(__FreeBSD_kernel__) || defined(__linux__) || \
104 defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX) || defined(__GNU__)
106 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
109 char fullpath[PATH_MAX];
111 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
112 if (!realpath(fullpath, ret))
114 if (stat(fullpath, &sb) != 0)
121 getprogpath(char ret[PATH_MAX], const char *bin)
125 /* First approach: absolute path. */
127 if (test_dir(ret, "/", bin) == 0)
132 /* Second approach: relative path. */
133 if (strchr(bin, '/')) {
135 if (!getcwd(cwd, PATH_MAX))
137 if (test_dir(ret, cwd, bin) == 0)
142 /* Third approach: $PATH */
143 if ((pv = getenv("PATH")) == nullptr)
148 while ((t = strsep(&s, ":")) != nullptr) {
149 if (test_dir(ret, t, bin) == 0) {
157 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
159 /// GetMainExecutable - Return the path to the main executable, given the
160 /// value of argv[0] from program startup.
161 std::string getMainExecutable(const char *argv0, void *MainAddr) {
162 #if defined(__APPLE__)
163 // On OS X the executable path is saved to the stack by dyld. Reading it
164 // from there is much faster than calling dladdr, especially for large
165 // binaries with symbols.
166 char exe_path[MAXPATHLEN];
167 uint32_t size = sizeof(exe_path);
168 if (_NSGetExecutablePath(exe_path, &size) == 0) {
169 char link_path[MAXPATHLEN];
170 if (realpath(exe_path, link_path))
173 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
174 defined(__minix) || defined(__DragonFly__) || \
175 defined(__FreeBSD_kernel__) || defined(_AIX)
176 char exe_path[PATH_MAX];
178 if (getprogpath(exe_path, argv0) != NULL)
180 #elif defined(__linux__) || defined(__CYGWIN__)
181 char exe_path[MAXPATHLEN];
182 StringRef aPath("/proc/self/exe");
183 if (sys::fs::exists(aPath)) {
184 // /proc is not always mounted under Linux (chroot for example).
185 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
189 // Null terminate the string for realpath. readlink never null
190 // terminates its output.
191 len = std::min(len, ssize_t(sizeof(exe_path) - 1));
192 exe_path[len] = '\0';
194 // On Linux, /proc/self/exe always looks through symlinks. However, on
195 // GNU/Hurd, /proc/self/exe is a symlink to the path that was used to start
196 // the program, and not the eventual binary file. Therefore, call realpath
197 // so this behaves the same on all platforms.
198 #if _POSIX_VERSION >= 200112 || defined(__GLIBC__)
199 char *real_path = realpath(exe_path, NULL);
200 std::string ret = std::string(real_path);
204 char real_path[MAXPATHLEN];
205 realpath(exe_path, real_path);
206 return std::string(real_path);
209 // Fall back to the classical detection.
210 if (getprogpath(exe_path, argv0))
213 #elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
214 // Use dladdr to get executable path if available.
216 int err = dladdr(MainAddr, &DLInfo);
220 // If the filename is a symlink, we need to resolve and return the location of
221 // the actual executable.
222 char link_path[MAXPATHLEN];
223 if (realpath(DLInfo.dli_fname, link_path))
226 #error GetMainExecutable is not implemented on this host yet.
231 TimePoint<> basic_file_status::getLastAccessedTime() const {
232 return toTimePoint(fs_st_atime, fs_st_atime_nsec);
235 TimePoint<> basic_file_status::getLastModificationTime() const {
236 return toTimePoint(fs_st_mtime, fs_st_mtime_nsec);
239 UniqueID file_status::getUniqueID() const {
240 return UniqueID(fs_st_dev, fs_st_ino);
243 uint32_t file_status::getLinkCount() const {
247 ErrorOr<space_info> disk_space(const Twine &Path) {
249 if (::STATVFS(Path.str().c_str(), &Vfs))
250 return std::error_code(errno, std::generic_category());
251 auto FrSize = STATVFS_F_FRSIZE(Vfs);
252 space_info SpaceInfo;
253 SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
254 SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
255 SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
259 std::error_code current_path(SmallVectorImpl<char> &result) {
262 const char *pwd = ::getenv("PWD");
263 llvm::sys::fs::file_status PWDStatus, DotStatus;
264 if (pwd && llvm::sys::path::is_absolute(pwd) &&
265 !llvm::sys::fs::status(pwd, PWDStatus) &&
266 !llvm::sys::fs::status(".", DotStatus) &&
267 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
268 result.append(pwd, pwd + strlen(pwd));
269 return std::error_code();
273 result.reserve(MAXPATHLEN);
276 result.reserve(1024);
280 if (::getcwd(result.data(), result.capacity()) == nullptr) {
281 // See if there was a real error.
283 return std::error_code(errno, std::generic_category());
284 // Otherwise there just wasn't enough space.
285 result.reserve(result.capacity() * 2);
290 result.set_size(strlen(result.data()));
291 return std::error_code();
294 std::error_code set_current_path(const Twine &path) {
295 SmallString<128> path_storage;
296 StringRef p = path.toNullTerminatedStringRef(path_storage);
298 if (::chdir(p.begin()) == -1)
299 return std::error_code(errno, std::generic_category());
301 return std::error_code();
304 std::error_code create_directory(const Twine &path, bool IgnoreExisting,
306 SmallString<128> path_storage;
307 StringRef p = path.toNullTerminatedStringRef(path_storage);
309 if (::mkdir(p.begin(), Perms) == -1) {
310 if (errno != EEXIST || !IgnoreExisting)
311 return std::error_code(errno, std::generic_category());
314 return std::error_code();
317 // Note that we are using symbolic link because hard links are not supported by
318 // all filesystems (SMB doesn't).
319 std::error_code create_link(const Twine &to, const Twine &from) {
321 SmallString<128> from_storage;
322 SmallString<128> to_storage;
323 StringRef f = from.toNullTerminatedStringRef(from_storage);
324 StringRef t = to.toNullTerminatedStringRef(to_storage);
326 if (::symlink(t.begin(), f.begin()) == -1)
327 return std::error_code(errno, std::generic_category());
329 return std::error_code();
332 std::error_code create_hard_link(const Twine &to, const Twine &from) {
334 SmallString<128> from_storage;
335 SmallString<128> to_storage;
336 StringRef f = from.toNullTerminatedStringRef(from_storage);
337 StringRef t = to.toNullTerminatedStringRef(to_storage);
339 if (::link(t.begin(), f.begin()) == -1)
340 return std::error_code(errno, std::generic_category());
342 return std::error_code();
345 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
346 SmallString<128> path_storage;
347 StringRef p = path.toNullTerminatedStringRef(path_storage);
350 if (lstat(p.begin(), &buf) != 0) {
351 if (errno != ENOENT || !IgnoreNonExisting)
352 return std::error_code(errno, std::generic_category());
353 return std::error_code();
356 // Note: this check catches strange situations. In all cases, LLVM should
357 // only be involved in the creation and deletion of regular files. This
358 // check ensures that what we're trying to erase is a regular file. It
359 // effectively prevents LLVM from erasing things like /dev/null, any block
360 // special file, or other things that aren't "regular" files.
361 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
362 return make_error_code(errc::operation_not_permitted);
364 if (::remove(p.begin()) == -1) {
365 if (errno != ENOENT || !IgnoreNonExisting)
366 return std::error_code(errno, std::generic_category());
369 return std::error_code();
372 static bool is_local_impl(struct STATVFS &Vfs) {
373 #if defined(__linux__) || defined(__GNU__)
374 #ifndef NFS_SUPER_MAGIC
375 #define NFS_SUPER_MAGIC 0x6969
377 #ifndef SMB_SUPER_MAGIC
378 #define SMB_SUPER_MAGIC 0x517B
380 #ifndef CIFS_MAGIC_NUMBER
381 #define CIFS_MAGIC_NUMBER 0xFF534D42
384 switch ((uint32_t)Vfs.__f_type) {
386 switch ((uint32_t)Vfs.f_type) {
388 case NFS_SUPER_MAGIC:
389 case SMB_SUPER_MAGIC:
390 case CIFS_MAGIC_NUMBER:
395 #elif defined(__CYGWIN__)
396 // Cygwin doesn't expose this information; would need to use Win32 API.
398 #elif defined(__Fuchsia__)
399 // Fuchsia doesn't yet support remote filesystem mounts.
401 #elif defined(__HAIKU__)
402 // Haiku doesn't expose this information.
405 // statvfs::f_basetype contains a null-terminated FSType name of the mounted target
406 StringRef fstype(Vfs.f_basetype);
407 // NFS is the only non-local fstype??
408 return !fstype.equals("nfs");
410 return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
414 std::error_code is_local(const Twine &Path, bool &Result) {
416 if (::STATVFS(Path.str().c_str(), &Vfs))
417 return std::error_code(errno, std::generic_category());
419 Result = is_local_impl(Vfs);
420 return std::error_code();
423 std::error_code is_local(int FD, bool &Result) {
425 if (::FSTATVFS(FD, &Vfs))
426 return std::error_code(errno, std::generic_category());
428 Result = is_local_impl(Vfs);
429 return std::error_code();
432 std::error_code rename(const Twine &from, const Twine &to) {
434 SmallString<128> from_storage;
435 SmallString<128> to_storage;
436 StringRef f = from.toNullTerminatedStringRef(from_storage);
437 StringRef t = to.toNullTerminatedStringRef(to_storage);
439 if (::rename(f.begin(), t.begin()) == -1)
440 return std::error_code(errno, std::generic_category());
442 return std::error_code();
445 std::error_code resize_file(int FD, uint64_t Size) {
446 #if defined(HAVE_POSIX_FALLOCATE)
447 // If we have posix_fallocate use it. Unlike ftruncate it always allocates
448 // space, so we get an error if the disk is full.
449 if (int Err = ::posix_fallocate(FD, 0, Size)) {
450 if (Err != EINVAL && Err != EOPNOTSUPP)
451 return std::error_code(Err, std::generic_category());
454 // Use ftruncate as a fallback. It may or may not allocate space. At least on
455 // OS X with HFS+ it does.
456 if (::ftruncate(FD, Size) == -1)
457 return std::error_code(errno, std::generic_category());
459 return std::error_code();
462 static int convertAccessMode(AccessMode Mode) {
464 case AccessMode::Exist:
466 case AccessMode::Write:
468 case AccessMode::Execute:
469 return R_OK | X_OK; // scripts also need R_OK.
471 llvm_unreachable("invalid enum");
474 std::error_code access(const Twine &Path, AccessMode Mode) {
475 SmallString<128> PathStorage;
476 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
478 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
479 return std::error_code(errno, std::generic_category());
481 if (Mode == AccessMode::Execute) {
482 // Don't say that directories are executable.
484 if (0 != stat(P.begin(), &buf))
485 return errc::permission_denied;
486 if (!S_ISREG(buf.st_mode))
487 return errc::permission_denied;
490 return std::error_code();
493 bool can_execute(const Twine &Path) {
494 return !access(Path, AccessMode::Execute);
497 bool equivalent(file_status A, file_status B) {
498 assert(status_known(A) && status_known(B));
499 return A.fs_st_dev == B.fs_st_dev &&
500 A.fs_st_ino == B.fs_st_ino;
503 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
504 file_status fsA, fsB;
505 if (std::error_code ec = status(A, fsA))
507 if (std::error_code ec = status(B, fsB))
509 result = equivalent(fsA, fsB);
510 return std::error_code();
513 static void expandTildeExpr(SmallVectorImpl<char> &Path) {
514 StringRef PathStr(Path.begin(), Path.size());
515 if (PathStr.empty() || !PathStr.startswith("~"))
518 PathStr = PathStr.drop_front();
520 PathStr.take_until([](char c) { return path::is_separator(c); });
521 StringRef Remainder = PathStr.substr(Expr.size() + 1);
522 SmallString<128> Storage;
524 // This is just ~/..., resolve it to the current user's home dir.
525 if (!path::home_directory(Storage)) {
526 // For some reason we couldn't get the home directory. Just exit.
530 // Overwrite the first character and insert the rest.
531 Path[0] = Storage[0];
532 Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
536 // This is a string of the form ~username/, look up this user's entry in the
537 // password database.
538 struct passwd *Entry = nullptr;
539 std::string User = Expr.str();
540 Entry = ::getpwnam(User.c_str());
543 // Unable to look up the entry, just return back the original path.
549 Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
550 llvm::sys::path::append(Path, Storage);
554 void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
556 if (path.isTriviallyEmpty())
560 expandTildeExpr(dest);
565 static file_type typeForMode(mode_t Mode) {
567 return file_type::directory_file;
568 else if (S_ISREG(Mode))
569 return file_type::regular_file;
570 else if (S_ISBLK(Mode))
571 return file_type::block_file;
572 else if (S_ISCHR(Mode))
573 return file_type::character_file;
574 else if (S_ISFIFO(Mode))
575 return file_type::fifo_file;
576 else if (S_ISSOCK(Mode))
577 return file_type::socket_file;
578 else if (S_ISLNK(Mode))
579 return file_type::symlink_file;
580 return file_type::type_unknown;
583 static std::error_code fillStatus(int StatRet, const struct stat &Status,
584 file_status &Result) {
586 std::error_code EC(errno, std::generic_category());
587 if (EC == errc::no_such_file_or_directory)
588 Result = file_status(file_type::file_not_found);
590 Result = file_status(file_type::status_error);
594 uint32_t atime_nsec, mtime_nsec;
595 #if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
596 atime_nsec = Status.st_atimespec.tv_nsec;
597 mtime_nsec = Status.st_mtimespec.tv_nsec;
598 #elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
599 atime_nsec = Status.st_atim.tv_nsec;
600 mtime_nsec = Status.st_mtim.tv_nsec;
602 atime_nsec = mtime_nsec = 0;
605 perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
606 Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev,
607 Status.st_nlink, Status.st_ino,
608 Status.st_atime, atime_nsec, Status.st_mtime, mtime_nsec,
609 Status.st_uid, Status.st_gid, Status.st_size);
611 return std::error_code();
614 std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
615 SmallString<128> PathStorage;
616 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
619 int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
620 return fillStatus(StatRet, Status, Result);
623 std::error_code status(int FD, file_status &Result) {
625 int StatRet = ::fstat(FD, &Status);
626 return fillStatus(StatRet, Status, Result);
629 std::error_code setPermissions(const Twine &Path, perms Permissions) {
630 SmallString<128> PathStorage;
631 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
633 if (::chmod(P.begin(), Permissions))
634 return std::error_code(errno, std::generic_category());
635 return std::error_code();
638 std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
639 TimePoint<> ModificationTime) {
640 #if defined(HAVE_FUTIMENS)
642 Times[0] = sys::toTimeSpec(AccessTime);
643 Times[1] = sys::toTimeSpec(ModificationTime);
644 if (::futimens(FD, Times))
645 return std::error_code(errno, std::generic_category());
646 return std::error_code();
647 #elif defined(HAVE_FUTIMES)
649 Times[0] = sys::toTimeVal(
650 std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
652 sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
654 if (::futimes(FD, Times))
655 return std::error_code(errno, std::generic_category());
656 return std::error_code();
658 #warning Missing futimes() and futimens()
659 return make_error_code(errc::function_not_supported);
663 std::error_code mapped_file_region::init(int FD, uint64_t Offset,
667 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
668 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
669 #if defined(__APPLE__)
670 //----------------------------------------------------------------------
671 // Newer versions of MacOSX have a flag that will allow us to read from
672 // binaries whose code signature is invalid without crashing by using
673 // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
674 // is mapped we can avoid crashing and return zeroes to any pages we try
675 // to read if the media becomes unavailable by using the
676 // MAP_RESILIENT_MEDIA flag. These flags are only usable when mapping
677 // with PROT_READ, so take care not to specify them otherwise.
678 //----------------------------------------------------------------------
679 if (Mode == readonly) {
680 #if defined(MAP_RESILIENT_CODESIGN)
681 flags |= MAP_RESILIENT_CODESIGN;
683 #if defined(MAP_RESILIENT_MEDIA)
684 flags |= MAP_RESILIENT_MEDIA;
687 #endif // #if defined (__APPLE__)
689 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
690 if (Mapping == MAP_FAILED)
691 return std::error_code(errno, std::generic_category());
692 return std::error_code();
695 mapped_file_region::mapped_file_region(int fd, mapmode mode, size_t length,
696 uint64_t offset, std::error_code &ec)
697 : Size(length), Mapping(), Mode(mode) {
699 ec = init(fd, offset, mode);
704 mapped_file_region::~mapped_file_region() {
706 ::munmap(Mapping, Size);
709 size_t mapped_file_region::size() const {
710 assert(Mapping && "Mapping failed but used anyway!");
714 char *mapped_file_region::data() const {
715 assert(Mapping && "Mapping failed but used anyway!");
716 return reinterpret_cast<char*>(Mapping);
719 const char *mapped_file_region::const_data() const {
720 assert(Mapping && "Mapping failed but used anyway!");
721 return reinterpret_cast<const char*>(Mapping);
724 int mapped_file_region::alignment() {
725 return Process::getPageSize();
728 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
730 bool follow_symlinks) {
731 SmallString<128> path_null(path);
732 DIR *directory = ::opendir(path_null.c_str());
734 return std::error_code(errno, std::generic_category());
736 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
737 // Add something for replace_filename to replace.
738 path::append(path_null, ".");
739 it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
740 return directory_iterator_increment(it);
743 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
744 if (it.IterationHandle)
745 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
746 it.IterationHandle = 0;
747 it.CurrentEntry = directory_entry();
748 return std::error_code();
751 static file_type direntType(dirent* Entry) {
752 // Most platforms provide the file type in the dirent: Linux/BSD/Mac.
753 // The DTTOIF macro lets us reuse our status -> type conversion.
754 #if defined(_DIRENT_HAVE_D_TYPE) && defined(DTTOIF)
755 return typeForMode(DTTOIF(Entry->d_type));
757 // Other platforms such as Solaris require a stat() to get the type.
758 return file_type::type_unknown;
762 std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
764 dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));
765 if (CurDir == nullptr && errno != 0) {
766 return std::error_code(errno, std::generic_category());
767 } else if (CurDir != nullptr) {
768 StringRef Name(CurDir->d_name);
769 if ((Name.size() == 1 && Name[0] == '.') ||
770 (Name.size() == 2 && Name[0] == '.' && Name[1] == '.'))
771 return directory_iterator_increment(It);
772 It.CurrentEntry.replace_filename(Name, direntType(CurDir));
774 return directory_iterator_destruct(It);
776 return std::error_code();
779 ErrorOr<basic_file_status> directory_entry::status() const {
781 if (auto EC = fs::status(Path, s, FollowSymlinks))
786 #if !defined(F_GETPATH)
787 static bool hasProcSelfFD() {
788 // If we have a /proc filesystem mounted, we can quickly establish the
789 // real name of the file with readlink
790 static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
795 static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
798 if (Access == FA_Read)
800 else if (Access == FA_Write)
802 else if (Access == (FA_Read | FA_Write))
805 // This is for compatibility with old code that assumed F_Append implied
806 // would open an existing file. See Windows/Path.inc for a longer comment.
807 if (Flags & F_Append)
808 Disp = CD_OpenAlways;
810 if (Disp == CD_CreateNew) {
811 Result |= O_CREAT; // Create if it doesn't exist.
812 Result |= O_EXCL; // Fail if it does.
813 } else if (Disp == CD_CreateAlways) {
814 Result |= O_CREAT; // Create if it doesn't exist.
815 Result |= O_TRUNC; // Truncate if it does.
816 } else if (Disp == CD_OpenAlways) {
817 Result |= O_CREAT; // Create if it doesn't exist.
818 } else if (Disp == CD_OpenExisting) {
819 // Nothing special, just don't add O_CREAT and we get these semantics.
822 if (Flags & F_Append)
826 if (!(Flags & OF_ChildInherit))
833 std::error_code openFile(const Twine &Name, int &ResultFD,
834 CreationDisposition Disp, FileAccess Access,
835 OpenFlags Flags, unsigned Mode) {
836 int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
838 SmallString<128> Storage;
839 StringRef P = Name.toNullTerminatedStringRef(Storage);
840 // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
841 // when open is overloaded, such as in Bionic.
842 auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
843 if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
844 return std::error_code(errno, std::generic_category());
846 if (!(Flags & OF_ChildInherit)) {
847 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
849 assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
852 return std::error_code();
855 Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,
856 FileAccess Access, OpenFlags Flags,
860 std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
862 return errorCodeToError(EC);
866 std::error_code openFileForRead(const Twine &Name, int &ResultFD,
868 SmallVectorImpl<char> *RealPath) {
870 openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
874 // Attempt to get the real name of the file, if the user asked
876 return std::error_code();
878 #if defined(F_GETPATH)
879 // When F_GETPATH is availble, it is the quickest way to get
880 // the real path name.
881 char Buffer[MAXPATHLEN];
882 if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
883 RealPath->append(Buffer, Buffer + strlen(Buffer));
885 char Buffer[PATH_MAX];
886 if (hasProcSelfFD()) {
888 snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
889 ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
891 RealPath->append(Buffer, Buffer + CharCount);
893 SmallString<128> Storage;
894 StringRef P = Name.toNullTerminatedStringRef(Storage);
896 // Use ::realpath to get the real path name
897 if (::realpath(P.begin(), Buffer) != nullptr)
898 RealPath->append(Buffer, Buffer + strlen(Buffer));
901 return std::error_code();
904 Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
905 SmallVectorImpl<char> *RealPath) {
907 std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
909 return errorCodeToError(EC);
913 void closeFile(file_t &F) {
918 template <typename T>
919 static std::error_code remove_directories_impl(const T &Entry,
922 directory_iterator Begin(Entry, EC, false);
923 directory_iterator End;
924 while (Begin != End) {
926 ErrorOr<basic_file_status> st = Item.status();
927 if (!st && !IgnoreErrors)
928 return st.getError();
930 if (is_directory(*st)) {
931 EC = remove_directories_impl(Item, IgnoreErrors);
932 if (EC && !IgnoreErrors)
936 EC = fs::remove(Item.path(), true);
937 if (EC && !IgnoreErrors)
941 if (EC && !IgnoreErrors)
944 return std::error_code();
947 std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
948 auto EC = remove_directories_impl(path, IgnoreErrors);
949 if (EC && !IgnoreErrors)
951 EC = fs::remove(path, true);
952 if (EC && !IgnoreErrors)
954 return std::error_code();
957 std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
960 if (path.isTriviallyEmpty())
961 return std::error_code();
964 SmallString<128> Storage;
965 path.toVector(Storage);
966 expandTildeExpr(Storage);
967 return real_path(Storage, dest, false);
970 SmallString<128> Storage;
971 StringRef P = path.toNullTerminatedStringRef(Storage);
972 char Buffer[PATH_MAX];
973 if (::realpath(P.begin(), Buffer) == nullptr)
974 return std::error_code(errno, std::generic_category());
975 dest.append(Buffer, Buffer + strlen(Buffer));
976 return std::error_code();
979 } // end namespace fs
983 bool home_directory(SmallVectorImpl<char> &result) {
984 char *RequestedDir = getenv("HOME");
986 struct passwd *pw = getpwuid(getuid());
987 if (pw && pw->pw_dir)
988 RequestedDir = pw->pw_dir;
994 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
998 static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
999 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
1000 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
1001 // macros defined in <unistd.h> on darwin >= 9
1002 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
1003 : _CS_DARWIN_USER_CACHE_DIR;
1004 size_t ConfLen = confstr(ConfName, nullptr, 0);
1007 Result.resize(ConfLen);
1008 ConfLen = confstr(ConfName, Result.data(), Result.size());
1009 } while (ConfLen > 0 && ConfLen != Result.size());
1012 assert(Result.back() == 0);
1023 static const char *getEnvTempDir() {
1024 // Check whether the temporary directory is specified by an environment
1026 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1027 for (const char *Env : EnvironmentVariables) {
1028 if (const char *Dir = std::getenv(Env))
1035 static const char *getDefaultTempDir(bool ErasedOnReboot) {
1046 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1049 if (ErasedOnReboot) {
1050 // There is no env variable for the cache directory.
1051 if (const char *RequestedDir = getEnvTempDir()) {
1052 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1057 if (getDarwinConfDir(ErasedOnReboot, Result))
1060 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1061 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1064 } // end namespace path
1066 } // end namespace sys
1067 } // end namespace llvm