OSDN Git Service

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