]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Support/Unix/Path.inc
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r303197, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Support / Unix / Path.inc
1 //===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Unix specific implementation of the Path API.
11 //
12 //===----------------------------------------------------------------------===//
13
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic UNIX code that
16 //===          is guaranteed to work on *all* UNIX variants.
17 //===----------------------------------------------------------------------===//
18
19 #include "Unix.h"
20 #include <limits.h>
21 #include <stdio.h>
22 #if HAVE_SYS_STAT_H
23 #include <sys/stat.h>
24 #endif
25 #if HAVE_FCNTL_H
26 #include <fcntl.h>
27 #endif
28 #ifdef HAVE_UNISTD_H
29 #include <unistd.h>
30 #endif
31 #ifdef HAVE_SYS_MMAN_H
32 #include <sys/mman.h>
33 #endif
34 #if HAVE_DIRENT_H
35 # include <dirent.h>
36 # define NAMLEN(dirent) strlen((dirent)->d_name)
37 #else
38 # define dirent direct
39 # define NAMLEN(dirent) (dirent)->d_namlen
40 # if HAVE_SYS_NDIR_H
41 #  include <sys/ndir.h>
42 # endif
43 # if HAVE_SYS_DIR_H
44 #  include <sys/dir.h>
45 # endif
46 # if HAVE_NDIR_H
47 #  include <ndir.h>
48 # endif
49 #endif
50
51 #include <pwd.h>
52
53 #ifdef __APPLE__
54 #include <mach-o/dyld.h>
55 #include <sys/attr.h>
56 #endif
57
58 // Both stdio.h and cstdio are included via different paths and
59 // stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
60 // either.
61 #undef ferror
62 #undef feof
63
64 // For GNU Hurd
65 #if defined(__GNU__) && !defined(PATH_MAX)
66 # define PATH_MAX 4096
67 #endif
68
69 #include <sys/types.h>
70 #if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) &&   \
71     !defined(__linux__)
72 #include <sys/statvfs.h>
73 #define STATVFS statvfs
74 #define FSTATVFS fstatvfs
75 #define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
76 #else
77 #if defined(__OpenBSD__) || defined(__FreeBSD__)
78 #include <sys/param.h>
79 #include <sys/mount.h>
80 #elif defined(__linux__)
81 #if defined(HAVE_LINUX_MAGIC_H)
82 #include <linux/magic.h>
83 #else
84 #if defined(HAVE_LINUX_NFS_FS_H)
85 #include <linux/nfs_fs.h>
86 #endif
87 #if defined(HAVE_LINUX_SMB_H)
88 #include <linux/smb.h>
89 #endif
90 #endif
91 #include <sys/vfs.h>
92 #else
93 #include <sys/mount.h>
94 #endif
95 #define STATVFS statfs
96 #define FSTATVFS fstatfs
97 #define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
98 #endif
99
100 #if defined(__NetBSD__)
101 #define STATVFS_F_FLAG(vfs) (vfs).f_flag
102 #else
103 #define STATVFS_F_FLAG(vfs) (vfs).f_flags
104 #endif
105
106 #if defined(__FreeBSD__) || defined(__NetBSD__)
107 #include <sys/sysctl.h>
108 #endif
109
110 using namespace llvm;
111
112 namespace llvm {
113 namespace sys  {
114 namespace fs {
115 #if defined(__Bitrig__) || defined(__OpenBSD__) || defined(__minix) || \
116     defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__) || \
117     defined(_AIX)
118 static int
119 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
120 {
121   struct stat sb;
122   char fullpath[PATH_MAX];
123
124   snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
125   if (!realpath(fullpath, ret))
126     return 1;
127   if (stat(fullpath, &sb) != 0)
128     return 1;
129
130   return 0;
131 }
132
133 static char *
134 getprogpath(char ret[PATH_MAX], const char *bin)
135 {
136   char *pv, *s, *t;
137
138   /* First approach: absolute path. */
139   if (bin[0] == '/') {
140     if (test_dir(ret, "/", bin) == 0)
141       return ret;
142     return nullptr;
143   }
144
145   /* Second approach: relative path. */
146   if (strchr(bin, '/')) {
147     char cwd[PATH_MAX];
148     if (!getcwd(cwd, PATH_MAX))
149       return nullptr;
150     if (test_dir(ret, cwd, bin) == 0)
151       return ret;
152     return nullptr;
153   }
154
155   /* Third approach: $PATH */
156   if ((pv = getenv("PATH")) == nullptr)
157     return nullptr;
158   s = pv = strdup(pv);
159   if (!pv)
160     return nullptr;
161   while ((t = strsep(&s, ":")) != nullptr) {
162     if (test_dir(ret, t, bin) == 0) {
163       free(pv);
164       return ret;
165     }
166   }
167   free(pv);
168   return nullptr;
169 }
170 #endif // Bitrig || OpenBSD || minix || linux || CYGWIN || DragonFly || AIX
171
172 /// GetMainExecutable - Return the path to the main executable, given the
173 /// value of argv[0] from program startup.
174 std::string getMainExecutable(const char *argv0, void *MainAddr) {
175 #if defined(__APPLE__)
176   // On OS X the executable path is saved to the stack by dyld. Reading it
177   // from there is much faster than calling dladdr, especially for large
178   // binaries with symbols.
179   char exe_path[MAXPATHLEN];
180   uint32_t size = sizeof(exe_path);
181   if (_NSGetExecutablePath(exe_path, &size) == 0) {
182     char link_path[MAXPATHLEN];
183     if (realpath(exe_path, link_path))
184       return link_path;
185   }
186 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
187   int mib[4];
188   mib[0] = CTL_KERN;
189 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
190   mib[1] = KERN_PROC;
191   mib[2] = KERN_PROC_PATHNAME;
192   mib[3] = -1;
193 #else
194   mib[1] = KERN_PROC_ARGS;
195   mib[2] = -1;
196   mib[3] = KERN_PROC_PATHNAME;
197 #endif
198   char exe_path[PATH_MAX];
199   size_t cb = sizeof(exe_path);
200   if (sysctl(mib, 4, exe_path, &cb, NULL, 0) == 0)
201     return exe_path;
202 #elif defined(__Bitrig__) || defined(__OpenBSD__) || defined(__minix) || \
203       defined(__DragonFly__) || defined(_AIX)
204   char exe_path[PATH_MAX];
205
206   if (getprogpath(exe_path, argv0) != NULL)
207     return exe_path;
208 #elif defined(__linux__) || defined(__CYGWIN__)
209   char exe_path[MAXPATHLEN];
210   StringRef aPath("/proc/self/exe");
211   if (sys::fs::exists(aPath)) {
212       // /proc is not always mounted under Linux (chroot for example).
213       ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
214       if (len >= 0)
215           return std::string(exe_path, len);
216   } else {
217       // Fall back to the classical detection.
218       if (getprogpath(exe_path, argv0))
219         return exe_path;
220   }
221 #elif defined(HAVE_DLFCN_H) && defined(HAVE_DLADDR)
222   // Use dladdr to get executable path if available.
223   Dl_info DLInfo;
224   int err = dladdr(MainAddr, &DLInfo);
225   if (err == 0)
226     return "";
227
228   // If the filename is a symlink, we need to resolve and return the location of
229   // the actual executable.
230   char link_path[MAXPATHLEN];
231   if (realpath(DLInfo.dli_fname, link_path))
232     return link_path;
233 #else
234 #error GetMainExecutable is not implemented on this host yet.
235 #endif
236   return "";
237 }
238
239 TimePoint<> file_status::getLastAccessedTime() const {
240   return toTimePoint(fs_st_atime);
241 }
242
243 TimePoint<> file_status::getLastModificationTime() const {
244   return toTimePoint(fs_st_mtime);
245 }
246
247 UniqueID file_status::getUniqueID() const {
248   return UniqueID(fs_st_dev, fs_st_ino);
249 }
250
251 uint32_t file_status::getLinkCount() const {
252   return fs_st_nlinks;
253 }
254
255 ErrorOr<space_info> disk_space(const Twine &Path) {
256   struct STATVFS Vfs;
257   if (::STATVFS(Path.str().c_str(), &Vfs))
258     return std::error_code(errno, std::generic_category());
259   auto FrSize = STATVFS_F_FRSIZE(Vfs);
260   space_info SpaceInfo;
261   SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
262   SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
263   SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
264   return SpaceInfo;
265 }
266
267 std::error_code current_path(SmallVectorImpl<char> &result) {
268   result.clear();
269
270   const char *pwd = ::getenv("PWD");
271   llvm::sys::fs::file_status PWDStatus, DotStatus;
272   if (pwd && llvm::sys::path::is_absolute(pwd) &&
273       !llvm::sys::fs::status(pwd, PWDStatus) &&
274       !llvm::sys::fs::status(".", DotStatus) &&
275       PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
276     result.append(pwd, pwd + strlen(pwd));
277     return std::error_code();
278   }
279
280 #ifdef MAXPATHLEN
281   result.reserve(MAXPATHLEN);
282 #else
283 // For GNU Hurd
284   result.reserve(1024);
285 #endif
286
287   while (true) {
288     if (::getcwd(result.data(), result.capacity()) == nullptr) {
289       // See if there was a real error.
290       if (errno != ENOMEM)
291         return std::error_code(errno, std::generic_category());
292       // Otherwise there just wasn't enough space.
293       result.reserve(result.capacity() * 2);
294     } else
295       break;
296   }
297
298   result.set_size(strlen(result.data()));
299   return std::error_code();
300 }
301
302 std::error_code set_current_path(const Twine &path) {
303   SmallString<128> path_storage;
304   StringRef p = path.toNullTerminatedStringRef(path_storage);
305
306   if (::chdir(p.begin()) == -1)
307     return std::error_code(errno, std::generic_category());
308
309   return std::error_code();
310 }
311
312 std::error_code create_directory(const Twine &path, bool IgnoreExisting,
313                                  perms Perms) {
314   SmallString<128> path_storage;
315   StringRef p = path.toNullTerminatedStringRef(path_storage);
316
317   if (::mkdir(p.begin(), Perms) == -1) {
318     if (errno != EEXIST || !IgnoreExisting)
319       return std::error_code(errno, std::generic_category());
320   }
321
322   return std::error_code();
323 }
324
325 // Note that we are using symbolic link because hard links are not supported by
326 // all filesystems (SMB doesn't).
327 std::error_code create_link(const Twine &to, const Twine &from) {
328   // Get arguments.
329   SmallString<128> from_storage;
330   SmallString<128> to_storage;
331   StringRef f = from.toNullTerminatedStringRef(from_storage);
332   StringRef t = to.toNullTerminatedStringRef(to_storage);
333
334   if (::symlink(t.begin(), f.begin()) == -1)
335     return std::error_code(errno, std::generic_category());
336
337   return std::error_code();
338 }
339
340 std::error_code create_hard_link(const Twine &to, const Twine &from) {
341   // Get arguments.
342   SmallString<128> from_storage;
343   SmallString<128> to_storage;
344   StringRef f = from.toNullTerminatedStringRef(from_storage);
345   StringRef t = to.toNullTerminatedStringRef(to_storage);
346
347   if (::link(t.begin(), f.begin()) == -1)
348     return std::error_code(errno, std::generic_category());
349
350   return std::error_code();
351 }
352
353 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
354   SmallString<128> path_storage;
355   StringRef p = path.toNullTerminatedStringRef(path_storage);
356
357   struct stat buf;
358   if (lstat(p.begin(), &buf) != 0) {
359     if (errno != ENOENT || !IgnoreNonExisting)
360       return std::error_code(errno, std::generic_category());
361     return std::error_code();
362   }
363
364   // Note: this check catches strange situations. In all cases, LLVM should
365   // only be involved in the creation and deletion of regular files.  This
366   // check ensures that what we're trying to erase is a regular file. It
367   // effectively prevents LLVM from erasing things like /dev/null, any block
368   // special file, or other things that aren't "regular" files.
369   if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
370     return make_error_code(errc::operation_not_permitted);
371
372   if (::remove(p.begin()) == -1) {
373     if (errno != ENOENT || !IgnoreNonExisting)
374       return std::error_code(errno, std::generic_category());
375   }
376
377   return std::error_code();
378 }
379
380 static bool is_local_impl(struct STATVFS &Vfs) {
381 #if defined(__linux__)
382 #ifndef NFS_SUPER_MAGIC
383 #define NFS_SUPER_MAGIC 0x6969
384 #endif
385 #ifndef SMB_SUPER_MAGIC
386 #define SMB_SUPER_MAGIC 0x517B
387 #endif
388 #ifndef CIFS_MAGIC_NUMBER
389 #define CIFS_MAGIC_NUMBER 0xFF534D42
390 #endif
391   switch ((uint32_t)Vfs.f_type) {
392   case NFS_SUPER_MAGIC:
393   case SMB_SUPER_MAGIC:
394   case CIFS_MAGIC_NUMBER:
395     return false;
396   default:
397     return true;
398   }
399 #elif defined(__CYGWIN__)
400   // Cygwin doesn't expose this information; would need to use Win32 API.
401   return false;
402 #else
403   return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
404 #endif
405 }
406
407 std::error_code is_local(const Twine &Path, bool &Result) {
408   struct STATVFS Vfs;
409   if (::STATVFS(Path.str().c_str(), &Vfs))
410     return std::error_code(errno, std::generic_category());
411
412   Result = is_local_impl(Vfs);
413   return std::error_code();
414 }
415
416 std::error_code is_local(int FD, bool &Result) {
417   struct STATVFS Vfs;
418   if (::FSTATVFS(FD, &Vfs))
419     return std::error_code(errno, std::generic_category());
420
421   Result = is_local_impl(Vfs);
422   return std::error_code();
423 }
424
425 std::error_code rename(const Twine &from, const Twine &to) {
426   // Get arguments.
427   SmallString<128> from_storage;
428   SmallString<128> to_storage;
429   StringRef f = from.toNullTerminatedStringRef(from_storage);
430   StringRef t = to.toNullTerminatedStringRef(to_storage);
431
432   if (::rename(f.begin(), t.begin()) == -1)
433     return std::error_code(errno, std::generic_category());
434
435   return std::error_code();
436 }
437
438 std::error_code resize_file(int FD, uint64_t Size) {
439 #if defined(HAVE_POSIX_FALLOCATE)
440   // If we have posix_fallocate use it. Unlike ftruncate it always allocates
441   // space, so we get an error if the disk is full.
442   if (int Err = ::posix_fallocate(FD, 0, Size)) {
443     if (Err != EOPNOTSUPP)
444       return std::error_code(Err, std::generic_category());
445   }
446 #endif
447   // Use ftruncate as a fallback. It may or may not allocate space. At least on
448   // OS X with HFS+ it does.
449   if (::ftruncate(FD, Size) == -1)
450     return std::error_code(errno, std::generic_category());
451
452   return std::error_code();
453 }
454
455 static int convertAccessMode(AccessMode Mode) {
456   switch (Mode) {
457   case AccessMode::Exist:
458     return F_OK;
459   case AccessMode::Write:
460     return W_OK;
461   case AccessMode::Execute:
462     return R_OK | X_OK; // scripts also need R_OK.
463   }
464   llvm_unreachable("invalid enum");
465 }
466
467 std::error_code access(const Twine &Path, AccessMode Mode) {
468   SmallString<128> PathStorage;
469   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
470
471   if (::access(P.begin(), convertAccessMode(Mode)) == -1)
472     return std::error_code(errno, std::generic_category());
473
474   if (Mode == AccessMode::Execute) {
475     // Don't say that directories are executable.
476     struct stat buf;
477     if (0 != stat(P.begin(), &buf))
478       return errc::permission_denied;
479     if (!S_ISREG(buf.st_mode))
480       return errc::permission_denied;
481   }
482
483   return std::error_code();
484 }
485
486 bool can_execute(const Twine &Path) {
487   return !access(Path, AccessMode::Execute);
488 }
489
490 bool equivalent(file_status A, file_status B) {
491   assert(status_known(A) && status_known(B));
492   return A.fs_st_dev == B.fs_st_dev &&
493          A.fs_st_ino == B.fs_st_ino;
494 }
495
496 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
497   file_status fsA, fsB;
498   if (std::error_code ec = status(A, fsA))
499     return ec;
500   if (std::error_code ec = status(B, fsB))
501     return ec;
502   result = equivalent(fsA, fsB);
503   return std::error_code();
504 }
505
506 static void expandTildeExpr(SmallVectorImpl<char> &Path) {
507   StringRef PathStr(Path.begin(), Path.size());
508   if (PathStr.empty() || !PathStr.startswith("~"))
509     return;
510
511   PathStr = PathStr.drop_front();
512   StringRef Expr =
513       PathStr.take_until([](char c) { return path::is_separator(c); });
514   StringRef Remainder = PathStr.substr(Expr.size() + 1);
515   SmallString<128> Storage;
516   if (Expr.empty()) {
517     // This is just ~/..., resolve it to the current user's home dir.
518     if (!path::home_directory(Storage)) {
519       // For some reason we couldn't get the home directory.  Just exit.
520       return;
521     }
522
523     // Overwrite the first character and insert the rest.
524     Path[0] = Storage[0];
525     Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
526     return;
527   }
528
529   // This is a string of the form ~username/, look up this user's entry in the
530   // password database.
531   struct passwd *Entry = nullptr;
532   std::string User = Expr.str();
533   Entry = ::getpwnam(User.c_str());
534
535   if (!Entry) {
536     // Unable to look up the entry, just return back the original path.
537     return;
538   }
539
540   Storage = Remainder;
541   Path.clear();
542   Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
543   llvm::sys::path::append(Path, Storage);
544 }
545
546 static std::error_code fillStatus(int StatRet, const struct stat &Status,
547                              file_status &Result) {
548   if (StatRet != 0) {
549     std::error_code ec(errno, std::generic_category());
550     if (ec == errc::no_such_file_or_directory)
551       Result = file_status(file_type::file_not_found);
552     else
553       Result = file_status(file_type::status_error);
554     return ec;
555   }
556
557   file_type Type = file_type::type_unknown;
558
559   if (S_ISDIR(Status.st_mode))
560     Type = file_type::directory_file;
561   else if (S_ISREG(Status.st_mode))
562     Type = file_type::regular_file;
563   else if (S_ISBLK(Status.st_mode))
564     Type = file_type::block_file;
565   else if (S_ISCHR(Status.st_mode))
566     Type = file_type::character_file;
567   else if (S_ISFIFO(Status.st_mode))
568     Type = file_type::fifo_file;
569   else if (S_ISSOCK(Status.st_mode))
570     Type = file_type::socket_file;
571   else if (S_ISLNK(Status.st_mode))
572     Type = file_type::symlink_file;
573
574   perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
575   Result = file_status(Type, Perms, Status.st_dev, Status.st_nlink,
576                        Status.st_ino, Status.st_atime, Status.st_mtime,
577                        Status.st_uid, Status.st_gid, Status.st_size);
578
579   return std::error_code();
580 }
581
582 std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
583   SmallString<128> PathStorage;
584   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
585
586   struct stat Status;
587   int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
588   return fillStatus(StatRet, Status, Result);
589 }
590
591 std::error_code status(int FD, file_status &Result) {
592   struct stat Status;
593   int StatRet = ::fstat(FD, &Status);
594   return fillStatus(StatRet, Status, Result);
595 }
596
597 std::error_code setPermissions(const Twine &Path, perms Permissions) {
598   SmallString<128> PathStorage;
599   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
600
601   if (::chmod(P.begin(), Permissions))
602     return std::error_code(errno, std::generic_category());
603   return std::error_code();
604 }
605
606 std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time) {
607 #if defined(HAVE_FUTIMENS)
608   timespec Times[2];
609   Times[0] = Times[1] = sys::toTimeSpec(Time);
610   if (::futimens(FD, Times))
611     return std::error_code(errno, std::generic_category());
612   return std::error_code();
613 #elif defined(HAVE_FUTIMES)
614   timeval Times[2];
615   Times[0] = Times[1] = sys::toTimeVal(
616       std::chrono::time_point_cast<std::chrono::microseconds>(Time));
617   if (::futimes(FD, Times))
618     return std::error_code(errno, std::generic_category());
619   return std::error_code();
620 #else
621 #warning Missing futimes() and futimens()
622   return make_error_code(errc::function_not_supported);
623 #endif
624 }
625
626 std::error_code mapped_file_region::init(int FD, uint64_t Offset,
627                                          mapmode Mode) {
628   assert(Size != 0);
629
630   int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
631   int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
632 #if defined(__APPLE__)
633   //----------------------------------------------------------------------
634   // Newer versions of MacOSX have a flag that will allow us to read from
635   // binaries whose code signature is invalid without crashing by using
636   // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
637   // is mapped we can avoid crashing and return zeroes to any pages we try
638   // to read if the media becomes unavailable by using the
639   // MAP_RESILIENT_MEDIA flag.  These flags are only usable when mapping
640   // with PROT_READ, so take care not to specify them otherwise.
641   //----------------------------------------------------------------------
642   if (Mode == readonly) {
643 #if defined(MAP_RESILIENT_CODESIGN)
644     flags |= MAP_RESILIENT_CODESIGN;
645 #endif
646 #if defined(MAP_RESILIENT_MEDIA)
647     flags |= MAP_RESILIENT_MEDIA;
648 #endif
649   }
650 #endif // #if defined (__APPLE__)
651
652   Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
653   if (Mapping == MAP_FAILED)
654     return std::error_code(errno, std::generic_category());
655   return std::error_code();
656 }
657
658 mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
659                                        uint64_t offset, std::error_code &ec)
660     : Size(length), Mapping() {
661   // Make sure that the requested size fits within SIZE_T.
662   if (length > std::numeric_limits<size_t>::max()) {
663     ec = make_error_code(errc::invalid_argument);
664     return;
665   }
666
667   ec = init(fd, offset, mode);
668   if (ec)
669     Mapping = nullptr;
670 }
671
672 mapped_file_region::~mapped_file_region() {
673   if (Mapping)
674     ::munmap(Mapping, Size);
675 }
676
677 uint64_t mapped_file_region::size() const {
678   assert(Mapping && "Mapping failed but used anyway!");
679   return Size;
680 }
681
682 char *mapped_file_region::data() const {
683   assert(Mapping && "Mapping failed but used anyway!");
684   return reinterpret_cast<char*>(Mapping);
685 }
686
687 const char *mapped_file_region::const_data() const {
688   assert(Mapping && "Mapping failed but used anyway!");
689   return reinterpret_cast<const char*>(Mapping);
690 }
691
692 int mapped_file_region::alignment() {
693   return Process::getPageSize();
694 }
695
696 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
697                                                      StringRef path,
698                                                      bool follow_symlinks) {
699   SmallString<128> path_null(path);
700   DIR *directory = ::opendir(path_null.c_str());
701   if (!directory)
702     return std::error_code(errno, std::generic_category());
703
704   it.IterationHandle = reinterpret_cast<intptr_t>(directory);
705   // Add something for replace_filename to replace.
706   path::append(path_null, ".");
707   it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
708   return directory_iterator_increment(it);
709 }
710
711 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
712   if (it.IterationHandle)
713     ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
714   it.IterationHandle = 0;
715   it.CurrentEntry = directory_entry();
716   return std::error_code();
717 }
718
719 std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
720   errno = 0;
721   dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
722   if (cur_dir == nullptr && errno != 0) {
723     return std::error_code(errno, std::generic_category());
724   } else if (cur_dir != nullptr) {
725     StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
726     if ((name.size() == 1 && name[0] == '.') ||
727         (name.size() == 2 && name[0] == '.' && name[1] == '.'))
728       return directory_iterator_increment(it);
729     it.CurrentEntry.replace_filename(name);
730   } else
731     return directory_iterator_destruct(it);
732
733   return std::error_code();
734 }
735
736 #if !defined(F_GETPATH)
737 static bool hasProcSelfFD() {
738   // If we have a /proc filesystem mounted, we can quickly establish the
739   // real name of the file with readlink
740   static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
741   return Result;
742 }
743 #endif
744
745 std::error_code openFileForRead(const Twine &Name, int &ResultFD,
746                                 SmallVectorImpl<char> *RealPath) {
747   SmallString<128> Storage;
748   StringRef P = Name.toNullTerminatedStringRef(Storage);
749   int OpenFlags = O_RDONLY;
750 #ifdef O_CLOEXEC
751   OpenFlags |= O_CLOEXEC;
752 #endif
753   while ((ResultFD = open(P.begin(), OpenFlags)) < 0) {
754     if (errno != EINTR)
755       return std::error_code(errno, std::generic_category());
756   }
757 #ifndef O_CLOEXEC
758   int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
759   (void)r;
760   assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
761 #endif
762   // Attempt to get the real name of the file, if the user asked
763   if(!RealPath)
764     return std::error_code();
765   RealPath->clear();
766 #if defined(F_GETPATH)
767   // When F_GETPATH is availble, it is the quickest way to get
768   // the real path name.
769   char Buffer[MAXPATHLEN];
770   if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
771     RealPath->append(Buffer, Buffer + strlen(Buffer));
772 #else
773   char Buffer[PATH_MAX];
774   if (hasProcSelfFD()) {
775     char ProcPath[64];
776     snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
777     ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
778     if (CharCount > 0)
779       RealPath->append(Buffer, Buffer + CharCount);
780   } else {
781     // Use ::realpath to get the real path name
782     if (::realpath(P.begin(), Buffer) != nullptr)
783       RealPath->append(Buffer, Buffer + strlen(Buffer));
784   }
785 #endif
786   return std::error_code();
787 }
788
789 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
790                             sys::fs::OpenFlags Flags, unsigned Mode) {
791   // Verify that we don't have both "append" and "excl".
792   assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
793          "Cannot specify both 'excl' and 'append' file creation flags!");
794
795   int OpenFlags = O_CREAT;
796
797 #ifdef O_CLOEXEC
798   OpenFlags |= O_CLOEXEC;
799 #endif
800
801   if (Flags & F_RW)
802     OpenFlags |= O_RDWR;
803   else
804     OpenFlags |= O_WRONLY;
805
806   if (Flags & F_Append)
807     OpenFlags |= O_APPEND;
808   else
809     OpenFlags |= O_TRUNC;
810
811   if (Flags & F_Excl)
812     OpenFlags |= O_EXCL;
813
814   SmallString<128> Storage;
815   StringRef P = Name.toNullTerminatedStringRef(Storage);
816   while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
817     if (errno != EINTR)
818       return std::error_code(errno, std::generic_category());
819   }
820 #ifndef O_CLOEXEC
821   int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
822   (void)r;
823   assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
824 #endif
825   return std::error_code();
826 }
827
828 std::error_code getPathFromOpenFD(int FD, SmallVectorImpl<char> &ResultPath) {
829   if (FD < 0)
830     return make_error_code(errc::bad_file_descriptor);
831
832 #if defined(F_GETPATH)
833   // When F_GETPATH is availble, it is the quickest way to get
834   // the path from a file descriptor.
835   ResultPath.reserve(MAXPATHLEN);
836   if (::fcntl(FD, F_GETPATH, ResultPath.begin()) == -1)
837     return std::error_code(errno, std::generic_category());
838
839   ResultPath.set_size(strlen(ResultPath.begin()));
840 #else
841   // If we have a /proc filesystem mounted, we can quickly establish the
842   // real name of the file with readlink. Otherwise, we don't know how to
843   // get the filename from a file descriptor. Give up.
844   if (!fs::hasProcSelfFD())
845     return make_error_code(errc::function_not_supported);
846
847   ResultPath.reserve(PATH_MAX);
848   char ProcPath[64];
849   snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", FD);
850   ssize_t CharCount = ::readlink(ProcPath, ResultPath.begin(), ResultPath.capacity());
851   if (CharCount < 0)
852       return std::error_code(errno, std::generic_category());
853
854   // Was the filename truncated?
855   if (static_cast<size_t>(CharCount) == ResultPath.capacity()) {
856     // Use lstat to get the size of the filename
857     struct stat sb;
858     if (::lstat(ProcPath, &sb) < 0)
859       return std::error_code(errno, std::generic_category());
860
861     ResultPath.reserve(sb.st_size + 1);
862     CharCount = ::readlink(ProcPath, ResultPath.begin(), ResultPath.capacity());
863     if (CharCount < 0)
864       return std::error_code(errno, std::generic_category());
865
866     // Test for race condition: did the link size change?
867     if (CharCount > sb.st_size)
868       return std::error_code(ENAMETOOLONG, std::generic_category());
869   }
870   ResultPath.set_size(static_cast<size_t>(CharCount));
871 #endif
872   return std::error_code();
873 }
874
875 template <typename T>
876 static std::error_code remove_directories_impl(const T &Entry,
877                                                bool IgnoreErrors) {
878   std::error_code EC;
879   directory_iterator Begin(Entry, EC, false);
880   directory_iterator End;
881   while (Begin != End) {
882     auto &Item = *Begin;
883     file_status st;
884     EC = Item.status(st);
885     if (EC && !IgnoreErrors)
886       return EC;
887
888     if (is_directory(st)) {
889       EC = remove_directories_impl(Item, IgnoreErrors);
890       if (EC && !IgnoreErrors)
891         return EC;
892     }
893
894     EC = fs::remove(Item.path(), true);
895     if (EC && !IgnoreErrors)
896       return EC;
897
898     Begin.increment(EC);
899     if (EC && !IgnoreErrors)
900       return EC;
901   }
902   return std::error_code();
903 }
904
905 std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
906   auto EC = remove_directories_impl(path, IgnoreErrors);
907   if (EC && !IgnoreErrors)
908     return EC;
909   EC = fs::remove(path, true);
910   if (EC && !IgnoreErrors)
911     return EC;
912   return std::error_code();
913 }
914
915 std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
916                           bool expand_tilde) {
917   dest.clear();
918   if (path.isTriviallyEmpty())
919     return std::error_code();
920
921   if (expand_tilde) {
922     SmallString<128> Storage;
923     path.toVector(Storage);
924     expandTildeExpr(Storage);
925     return real_path(Storage, dest, false);
926   }
927
928   int fd;
929   std::error_code EC = openFileForRead(path, fd, &dest);
930
931   if (EC)
932     return EC;
933   ::close(fd);
934   return std::error_code();
935 }
936
937 } // end namespace fs
938
939 namespace path {
940
941 bool home_directory(SmallVectorImpl<char> &result) {
942   char *RequestedDir = getenv("HOME");
943   if (!RequestedDir) {
944     struct passwd *pw = getpwuid(getuid());
945     if (pw && pw->pw_dir)
946       RequestedDir = pw->pw_dir;
947   }
948   if (!RequestedDir)
949     return false;
950
951   result.clear();
952   result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
953   return true;
954 }
955
956 static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
957   #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
958   // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
959   // macros defined in <unistd.h> on darwin >= 9
960   int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
961                          : _CS_DARWIN_USER_CACHE_DIR;
962   size_t ConfLen = confstr(ConfName, nullptr, 0);
963   if (ConfLen > 0) {
964     do {
965       Result.resize(ConfLen);
966       ConfLen = confstr(ConfName, Result.data(), Result.size());
967     } while (ConfLen > 0 && ConfLen != Result.size());
968
969     if (ConfLen > 0) {
970       assert(Result.back() == 0);
971       Result.pop_back();
972       return true;
973     }
974
975     Result.clear();
976   }
977   #endif
978   return false;
979 }
980
981 static bool getUserCacheDir(SmallVectorImpl<char> &Result) {
982   // First try using XDG_CACHE_HOME env variable,
983   // as specified in XDG Base Directory Specification at
984   // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
985   if (const char *XdgCacheDir = std::getenv("XDG_CACHE_HOME")) {
986     Result.clear();
987     Result.append(XdgCacheDir, XdgCacheDir + strlen(XdgCacheDir));
988     return true;
989   }
990
991   // Try Darwin configuration query
992   if (getDarwinConfDir(false, Result))
993     return true;
994
995   // Use "$HOME/.cache" if $HOME is available
996   if (home_directory(Result)) {
997     append(Result, ".cache");
998     return true;
999   }
1000
1001   return false;
1002 }
1003
1004 static const char *getEnvTempDir() {
1005   // Check whether the temporary directory is specified by an environment
1006   // variable.
1007   const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1008   for (const char *Env : EnvironmentVariables) {
1009     if (const char *Dir = std::getenv(Env))
1010       return Dir;
1011   }
1012
1013   return nullptr;
1014 }
1015
1016 static const char *getDefaultTempDir(bool ErasedOnReboot) {
1017 #ifdef P_tmpdir
1018   if ((bool)P_tmpdir)
1019     return P_tmpdir;
1020 #endif
1021
1022   if (ErasedOnReboot)
1023     return "/tmp";
1024   return "/var/tmp";
1025 }
1026
1027 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1028   Result.clear();
1029
1030   if (ErasedOnReboot) {
1031     // There is no env variable for the cache directory.
1032     if (const char *RequestedDir = getEnvTempDir()) {
1033       Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1034       return;
1035     }
1036   }
1037
1038   if (getDarwinConfDir(ErasedOnReboot, Result))
1039     return;
1040
1041   const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1042   Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1043 }
1044
1045 } // end namespace path
1046
1047 } // end namespace sys
1048 } // end namespace llvm