[MIPS GlobalISel] Select float constants
[llvm-complete.git] / lib / Support / Unix / Path.inc
blob57385baaf34bc98da158835bdc2448afde1417e4
1 //===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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 //===----------------------------------------------------------------------===//
18 #include "Unix.h"
19 #include <limits.h>
20 #include <stdio.h>
21 #if HAVE_SYS_STAT_H
22 #include <sys/stat.h>
23 #endif
24 #if HAVE_FCNTL_H
25 #include <fcntl.h>
26 #endif
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30 #ifdef HAVE_SYS_MMAN_H
31 #include <sys/mman.h>
32 #endif
34 #include <dirent.h>
35 #include <pwd.h>
37 #ifdef __APPLE__
38 #include <mach-o/dyld.h>
39 #include <sys/attr.h>
40 #elif defined(__DragonFly__)
41 #include <sys/mount.h>
42 #endif
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
46 // either.
47 #undef ferror
48 #undef feof
50 // For GNU Hurd
51 #if defined(__GNU__) && !defined(PATH_MAX)
52 # define PATH_MAX 4096
53 # define MAXPATHLEN 4096
54 #endif
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
63 #else
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>
70 #else
71 #if defined(HAVE_LINUX_NFS_FS_H)
72 #include <linux/nfs_fs.h>
73 #endif
74 #if defined(HAVE_LINUX_SMB_H)
75 #include <linux/smb.h>
76 #endif
77 #endif
78 #include <sys/vfs.h>
79 #else
80 #include <sys/mount.h>
81 #endif
82 #define STATVFS statfs
83 #define FSTATVFS fstatfs
84 #define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
85 #endif
87 #if defined(__NetBSD__) || defined(__DragonFly__) || defined(__GNU__)
88 #define STATVFS_F_FLAG(vfs) (vfs).f_flag
89 #else
90 #define STATVFS_F_FLAG(vfs) (vfs).f_flags
91 #endif
93 using namespace llvm;
95 namespace llvm {
96 namespace sys  {
97 namespace fs {
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__)
104 static int
105 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
107   struct stat sb;
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)
114     return 1;
115   if (!realpath(fullpath, ret))
116     return 1;
117   if (stat(fullpath, &sb) != 0)
118     return 1;
120   return 0;
123 static char *
124 getprogpath(char ret[PATH_MAX], const char *bin)
126   char *pv, *s, *t;
128   /* First approach: absolute path. */
129   if (bin[0] == '/') {
130     if (test_dir(ret, "/", bin) == 0)
131       return ret;
132     return nullptr;
133   }
135   /* Second approach: relative path. */
136   if (strchr(bin, '/')) {
137     char cwd[PATH_MAX];
138     if (!getcwd(cwd, PATH_MAX))
139       return nullptr;
140     if (test_dir(ret, cwd, bin) == 0)
141       return ret;
142     return nullptr;
143   }
145   /* Third approach: $PATH */
146   if ((pv = getenv("PATH")) == nullptr)
147     return nullptr;
148   s = pv = strdup(pv);
149   if (!pv)
150     return nullptr;
151   while ((t = strsep(&s, ":")) != nullptr) {
152     if (test_dir(ret, t, bin) == 0) {
153       free(pv);
154       return ret;
155     }
156   }
157   free(pv);
158   return nullptr;
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))
174       return link_path;
175   }
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)
182     return exe_path;
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));
189     if (len < 0)
190       return "";
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);
204     free(real_path);
205     return ret;
206 #else
207     char real_path[MAXPATHLEN];
208     realpath(exe_path, real_path);
209     return std::string(real_path);
210 #endif
211   } else {
212     // Fall back to the classical detection.
213     if (getprogpath(exe_path, argv0))
214       return exe_path;
215   }
216 #elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
217   // Use dladdr to get executable path if available.
218   Dl_info DLInfo;
219   int err = dladdr(MainAddr, &DLInfo);
220   if (err == 0)
221     return "";
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))
227     return link_path;
228 #else
229 #error GetMainExecutable is not implemented on this host yet.
230 #endif
231   return "";
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 {
247   return fs_st_nlinks;
250 ErrorOr<space_info> disk_space(const Twine &Path) {
251   struct STATVFS Vfs;
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;
259   return SpaceInfo;
262 std::error_code current_path(SmallVectorImpl<char> &result) {
263   result.clear();
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();
273   }
275 #ifdef MAXPATHLEN
276   result.reserve(MAXPATHLEN);
277 #else
278 // For GNU Hurd
279   result.reserve(1024);
280 #endif
282   while (true) {
283     if (::getcwd(result.data(), result.capacity()) == nullptr) {
284       // See if there was a real error.
285       if (errno != ENOMEM)
286         return std::error_code(errno, std::generic_category());
287       // Otherwise there just wasn't enough space.
288       result.reserve(result.capacity() * 2);
289     } else
290       break;
291   }
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,
308                                  perms Perms) {
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());
315   }
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) {
323   // Get arguments.
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) {
336   // Get arguments.
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);
352   struct stat buf;
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();
357   }
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());
370   }
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
379 #endif
380 #ifndef SMB_SUPER_MAGIC
381 #define SMB_SUPER_MAGIC 0x517B
382 #endif
383 #ifndef CIFS_MAGIC_NUMBER
384 #define CIFS_MAGIC_NUMBER 0xFF534D42
385 #endif
386 #ifdef __GNU__
387   switch ((uint32_t)Vfs.__f_type) {
388 #else
389   switch ((uint32_t)Vfs.f_type) {
390 #endif
391   case NFS_SUPER_MAGIC:
392   case SMB_SUPER_MAGIC:
393   case CIFS_MAGIC_NUMBER:
394     return false;
395   default:
396     return true;
397   }
398 #elif defined(__CYGWIN__)
399   // Cygwin doesn't expose this information; would need to use Win32 API.
400   return false;
401 #elif defined(__Fuchsia__)
402   // Fuchsia doesn't yet support remote filesystem mounts.
403   return true;
404 #elif defined(__HAIKU__)
405   // Haiku doesn't expose this information.
406   return false;
407 #elif defined(__sun)
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");
412 #else
413   return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
414 #endif
417 std::error_code is_local(const Twine &Path, bool &Result) {
418   struct STATVFS Vfs;
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) {
427   struct STATVFS Vfs;
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) {
436   // Get arguments.
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());
455   }
456 #endif
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) {
466   switch (Mode) {
467   case AccessMode::Exist:
468     return F_OK;
469   case AccessMode::Write:
470     return W_OK;
471   case AccessMode::Execute:
472     return R_OK | X_OK; // scripts also need R_OK.
473   }
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.
486     struct stat buf;
487     if (0 != stat(P.begin(), &buf))
488       return errc::permission_denied;
489     if (!S_ISREG(buf.st_mode))
490       return errc::permission_denied;
491   }
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))
509     return ec;
510   if (std::error_code ec = status(B, fsB))
511     return ec;
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("~"))
519     return;
521   PathStr = PathStr.drop_front();
522   StringRef Expr =
523       PathStr.take_until([](char c) { return path::is_separator(c); });
524   StringRef Remainder = PathStr.substr(Expr.size() + 1);
525   SmallString<128> Storage;
526   if (Expr.empty()) {
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.
530       return;
531     }
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());
536     return;
537   }
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());
545   if (!Entry) {
546     // Unable to look up the entry, just return back the original path.
547     return;
548   }
550   Storage = Remainder;
551   Path.clear();
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) {
558   dest.clear();
559   if (path.isTriviallyEmpty())
560     return;
562   path.toVector(dest);
563   expandTildeExpr(dest);
565   return;
568 static file_type typeForMode(mode_t Mode) {
569   if (S_ISDIR(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) {
588   if (StatRet != 0) {
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);
592     else
593       Result = file_status(file_type::status_error);
594     return EC;
595   }
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;
604 #else
605   atime_nsec = mtime_nsec = 0;
606 #endif
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);
621   struct stat Status;
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) {
627   struct stat Status;
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)
644   timespec Times[2];
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)
651   timeval Times[2];
652   Times[0] = sys::toTimeVal(
653       std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
654   Times[1] =
655       sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
656           ModificationTime));
657   if (::futimes(FD, Times))
658     return std::error_code(errno, std::generic_category());
659   return std::error_code();
660 #else
661 #warning Missing futimes() and futimens()
662   return make_error_code(errc::function_not_supported);
663 #endif
666 std::error_code mapped_file_region::init(int FD, uint64_t Offset,
667                                          mapmode Mode) {
668   assert(Size != 0);
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;
685 #endif
686 #if defined(MAP_RESILIENT_MEDIA)
687     flags |= MAP_RESILIENT_MEDIA;
688 #endif
689   }
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) {
701   (void)Mode;
702   ec = init(fd, offset, mode);
703   if (ec)
704     Mapping = nullptr;
707 mapped_file_region::~mapped_file_region() {
708   if (Mapping)
709     ::munmap(Mapping, Size);
712 size_t mapped_file_region::size() const {
713   assert(Mapping && "Mapping failed but used anyway!");
714   return Size;
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,
732                                                      StringRef path,
733                                                      bool follow_symlinks) {
734   SmallString<128> path_null(path);
735   DIR *directory = ::opendir(path_null.c_str());
736   if (!directory)
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));
759 #else
760   // Other platforms such as Solaris require a stat() to get the type.
761   return file_type::type_unknown;
762 #endif
765 std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
766   errno = 0;
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));
776   } else
777     return directory_iterator_destruct(It);
779   return std::error_code();
782 ErrorOr<basic_file_status> directory_entry::status() const {
783   file_status s;
784   if (auto EC = fs::status(Path, s, FollowSymlinks))
785     return EC;
786   return s;
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);
794   return Result;
796 #endif
798 static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
799                            FileAccess Access) {
800   int Result = 0;
801   if (Access == FA_Read)
802     Result |= O_RDONLY;
803   else if (Access == FA_Write)
804     Result |= O_WRONLY;
805   else if (Access == (FA_Read | FA_Write))
806     Result |= O_RDWR;
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.
823   }
825   if (Flags & F_Append)
826     Result |= O_APPEND;
828 #ifdef O_CLOEXEC
829   if (!(Flags & OF_ChildInherit))
830     Result |= O_CLOEXEC;
831 #endif
833   return Result;
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());
848 #ifndef O_CLOEXEC
849   if (!(Flags & OF_ChildInherit)) {
850     int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
851     (void)r;
852     assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
853   }
854 #endif
855   return std::error_code();
858 Expected<int> openNativeFile(const Twine &Name, CreationDisposition Disp,
859                              FileAccess Access, OpenFlags Flags,
860                              unsigned Mode) {
862   int FD;
863   std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
864   if (EC)
865     return errorCodeToError(EC);
866   return FD;
869 std::error_code openFileForRead(const Twine &Name, int &ResultFD,
870                                 OpenFlags Flags,
871                                 SmallVectorImpl<char> *RealPath) {
872   std::error_code EC =
873       openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
874   if (EC)
875     return EC;
877   // Attempt to get the real name of the file, if the user asked
878   if(!RealPath)
879     return std::error_code();
880   RealPath->clear();
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));
887 #else
888   char Buffer[PATH_MAX];
889   if (hasProcSelfFD()) {
890     char ProcPath[64];
891     snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
892     ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
893     if (CharCount > 0)
894       RealPath->append(Buffer, Buffer + CharCount);
895   } else {
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));
902   }
903 #endif
904   return std::error_code();
907 Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
908                                        SmallVectorImpl<char> *RealPath) {
909   file_t ResultFD;
910   std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
911   if (EC)
912     return errorCodeToError(EC);
913   return ResultFD;
916 void closeFile(file_t &F) {
917   ::close(F);
918   F = kInvalidFile;
921 template <typename T>
922 static std::error_code remove_directories_impl(const T &Entry,
923                                                bool IgnoreErrors) {
924   std::error_code EC;
925   directory_iterator Begin(Entry, EC, false);
926   directory_iterator End;
927   while (Begin != End) {
928     auto &Item = *Begin;
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)
936         return EC;
937     }
939     EC = fs::remove(Item.path(), true);
940     if (EC && !IgnoreErrors)
941       return EC;
943     Begin.increment(EC);
944     if (EC && !IgnoreErrors)
945       return EC;
946   }
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)
953     return EC;
954   EC = fs::remove(path, true);
955   if (EC && !IgnoreErrors)
956     return EC;
957   return std::error_code();
960 std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
961                           bool expand_tilde) {
962   dest.clear();
963   if (path.isTriviallyEmpty())
964     return std::error_code();
966   if (expand_tilde) {
967     SmallString<128> Storage;
968     path.toVector(Storage);
969     expandTildeExpr(Storage);
970     return real_path(Storage, dest, false);
971   }
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
984 namespace path {
986 bool home_directory(SmallVectorImpl<char> &result) {
987   char *RequestedDir = getenv("HOME");
988   if (!RequestedDir) {
989     struct passwd *pw = getpwuid(getuid());
990     if (pw && pw->pw_dir)
991       RequestedDir = pw->pw_dir;
992   }
993   if (!RequestedDir)
994     return false;
996   result.clear();
997   result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
998   return true;
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);
1008   if (ConfLen > 0) {
1009     do {
1010       Result.resize(ConfLen);
1011       ConfLen = confstr(ConfName, Result.data(), Result.size());
1012     } while (ConfLen > 0 && ConfLen != Result.size());
1014     if (ConfLen > 0) {
1015       assert(Result.back() == 0);
1016       Result.pop_back();
1017       return true;
1018     }
1020     Result.clear();
1021   }
1022   #endif
1023   return false;
1026 static const char *getEnvTempDir() {
1027   // Check whether the temporary directory is specified by an environment
1028   // variable.
1029   const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1030   for (const char *Env : EnvironmentVariables) {
1031     if (const char *Dir = std::getenv(Env))
1032       return Dir;
1033   }
1035   return nullptr;
1038 static const char *getDefaultTempDir(bool ErasedOnReboot) {
1039 #ifdef P_tmpdir
1040   if ((bool)P_tmpdir)
1041     return P_tmpdir;
1042 #endif
1044   if (ErasedOnReboot)
1045     return "/tmp";
1046   return "/var/tmp";
1049 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1050   Result.clear();
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));
1056       return;
1057     }
1058   }
1060   if (getDarwinConfDir(ErasedOnReboot, Result))
1061     return;
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