OSDN Git Service

[Support] Provide linux/magic.h fallback for older kernels
[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 #else
376   return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
377 #endif
378 }
379
380 std::error_code is_local(const Twine &Path, bool &Result) {
381   struct STATVFS Vfs;
382   if (::STATVFS(Path.str().c_str(), &Vfs))
383     return std::error_code(errno, std::generic_category());
384
385   Result = is_local_impl(Vfs);
386   return std::error_code();
387 }
388
389 std::error_code is_local(int FD, bool &Result) {
390   struct STATVFS Vfs;
391   if (::FSTATVFS(FD, &Vfs))
392     return std::error_code(errno, std::generic_category());
393
394   Result = is_local_impl(Vfs);
395   return std::error_code();
396 }
397
398 std::error_code rename(const Twine &from, const Twine &to) {
399   // Get arguments.
400   SmallString<128> from_storage;
401   SmallString<128> to_storage;
402   StringRef f = from.toNullTerminatedStringRef(from_storage);
403   StringRef t = to.toNullTerminatedStringRef(to_storage);
404
405   if (::rename(f.begin(), t.begin()) == -1)
406     return std::error_code(errno, std::generic_category());
407
408   return std::error_code();
409 }
410
411 std::error_code resize_file(int FD, uint64_t Size) {
412 #if defined(HAVE_POSIX_FALLOCATE)
413   // If we have posix_fallocate use it. Unlike ftruncate it always allocates
414   // space, so we get an error if the disk is full.
415   if (int Err = ::posix_fallocate(FD, 0, Size))
416     return std::error_code(Err, std::generic_category());
417 #else
418   // Use ftruncate as a fallback. It may or may not allocate space. At least on
419   // OS X with HFS+ it does.
420   if (::ftruncate(FD, Size) == -1)
421     return std::error_code(errno, std::generic_category());
422 #endif
423
424   return std::error_code();
425 }
426
427 static int convertAccessMode(AccessMode Mode) {
428   switch (Mode) {
429   case AccessMode::Exist:
430     return F_OK;
431   case AccessMode::Write:
432     return W_OK;
433   case AccessMode::Execute:
434     return R_OK | X_OK; // scripts also need R_OK.
435   }
436   llvm_unreachable("invalid enum");
437 }
438
439 std::error_code access(const Twine &Path, AccessMode Mode) {
440   SmallString<128> PathStorage;
441   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
442
443   if (::access(P.begin(), convertAccessMode(Mode)) == -1)
444     return std::error_code(errno, std::generic_category());
445
446   if (Mode == AccessMode::Execute) {
447     // Don't say that directories are executable.
448     struct stat buf;
449     if (0 != stat(P.begin(), &buf))
450       return errc::permission_denied;
451     if (!S_ISREG(buf.st_mode))
452       return errc::permission_denied;
453   }
454
455   return std::error_code();
456 }
457
458 bool can_execute(const Twine &Path) {
459   return !access(Path, AccessMode::Execute);
460 }
461
462 bool equivalent(file_status A, file_status B) {
463   assert(status_known(A) && status_known(B));
464   return A.fs_st_dev == B.fs_st_dev &&
465          A.fs_st_ino == B.fs_st_ino;
466 }
467
468 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
469   file_status fsA, fsB;
470   if (std::error_code ec = status(A, fsA))
471     return ec;
472   if (std::error_code ec = status(B, fsB))
473     return ec;
474   result = equivalent(fsA, fsB);
475   return std::error_code();
476 }
477
478 static std::error_code fillStatus(int StatRet, const struct stat &Status,
479                              file_status &Result) {
480   if (StatRet != 0) {
481     std::error_code ec(errno, std::generic_category());
482     if (ec == errc::no_such_file_or_directory)
483       Result = file_status(file_type::file_not_found);
484     else
485       Result = file_status(file_type::status_error);
486     return ec;
487   }
488
489   file_type Type = file_type::type_unknown;
490
491   if (S_ISDIR(Status.st_mode))
492     Type = file_type::directory_file;
493   else if (S_ISREG(Status.st_mode))
494     Type = file_type::regular_file;
495   else if (S_ISBLK(Status.st_mode))
496     Type = file_type::block_file;
497   else if (S_ISCHR(Status.st_mode))
498     Type = file_type::character_file;
499   else if (S_ISFIFO(Status.st_mode))
500     Type = file_type::fifo_file;
501   else if (S_ISSOCK(Status.st_mode))
502     Type = file_type::socket_file;
503
504   perms Perms = static_cast<perms>(Status.st_mode);
505   Result =
506       file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_atime,
507                   Status.st_mtime, Status.st_uid, Status.st_gid,
508                   Status.st_size);
509
510   return std::error_code();
511 }
512
513 std::error_code status(const Twine &Path, file_status &Result) {
514   SmallString<128> PathStorage;
515   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
516
517   struct stat Status;
518   int StatRet = ::stat(P.begin(), &Status);
519   return fillStatus(StatRet, Status, Result);
520 }
521
522 std::error_code status(int FD, file_status &Result) {
523   struct stat Status;
524   int StatRet = ::fstat(FD, &Status);
525   return fillStatus(StatRet, Status, Result);
526 }
527
528 std::error_code setLastModificationAndAccessTime(int FD, TimePoint<> Time) {
529 #if defined(HAVE_FUTIMENS)
530   timespec Times[2];
531   Times[0] = Times[1] = sys::toTimeSpec(Time);
532   if (::futimens(FD, Times))
533     return std::error_code(errno, std::generic_category());
534   return std::error_code();
535 #elif defined(HAVE_FUTIMES)
536   timeval Times[2];
537   Times[0] = Times[1] = sys::toTimeVal(
538       std::chrono::time_point_cast<std::chrono::microseconds>(Time));
539   if (::futimes(FD, Times))
540     return std::error_code(errno, std::generic_category());
541   return std::error_code();
542 #else
543 #warning Missing futimes() and futimens()
544   return make_error_code(errc::function_not_supported);
545 #endif
546 }
547
548 std::error_code mapped_file_region::init(int FD, uint64_t Offset,
549                                          mapmode Mode) {
550   assert(Size != 0);
551
552   int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
553   int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
554
555   Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
556   if (Mapping == MAP_FAILED)
557     return std::error_code(errno, std::generic_category());
558   return std::error_code();
559 }
560
561 mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
562                                        uint64_t offset, std::error_code &ec)
563     : Size(length), Mapping() {
564   // Make sure that the requested size fits within SIZE_T.
565   if (length > std::numeric_limits<size_t>::max()) {
566     ec = make_error_code(errc::invalid_argument);
567     return;
568   }
569
570   ec = init(fd, offset, mode);
571   if (ec)
572     Mapping = nullptr;
573 }
574
575 mapped_file_region::~mapped_file_region() {
576   if (Mapping)
577     ::munmap(Mapping, Size);
578 }
579
580 uint64_t mapped_file_region::size() const {
581   assert(Mapping && "Mapping failed but used anyway!");
582   return Size;
583 }
584
585 char *mapped_file_region::data() const {
586   assert(Mapping && "Mapping failed but used anyway!");
587   return reinterpret_cast<char*>(Mapping);
588 }
589
590 const char *mapped_file_region::const_data() const {
591   assert(Mapping && "Mapping failed but used anyway!");
592   return reinterpret_cast<const char*>(Mapping);
593 }
594
595 int mapped_file_region::alignment() {
596   return Process::getPageSize();
597 }
598
599 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
600                                                 StringRef path){
601   SmallString<128> path_null(path);
602   DIR *directory = ::opendir(path_null.c_str());
603   if (!directory)
604     return std::error_code(errno, std::generic_category());
605
606   it.IterationHandle = reinterpret_cast<intptr_t>(directory);
607   // Add something for replace_filename to replace.
608   path::append(path_null, ".");
609   it.CurrentEntry = directory_entry(path_null.str());
610   return directory_iterator_increment(it);
611 }
612
613 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
614   if (it.IterationHandle)
615     ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
616   it.IterationHandle = 0;
617   it.CurrentEntry = directory_entry();
618   return std::error_code();
619 }
620
621 std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
622   errno = 0;
623   dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
624   if (cur_dir == nullptr && errno != 0) {
625     return std::error_code(errno, std::generic_category());
626   } else if (cur_dir != nullptr) {
627     StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
628     if ((name.size() == 1 && name[0] == '.') ||
629         (name.size() == 2 && name[0] == '.' && name[1] == '.'))
630       return directory_iterator_increment(it);
631     it.CurrentEntry.replace_filename(name);
632   } else
633     return directory_iterator_destruct(it);
634
635   return std::error_code();
636 }
637
638 #if !defined(F_GETPATH)
639 static bool hasProcSelfFD() {
640   // If we have a /proc filesystem mounted, we can quickly establish the
641   // real name of the file with readlink
642   static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
643   return Result;
644 }
645 #endif
646
647 std::error_code openFileForRead(const Twine &Name, int &ResultFD,
648                                 SmallVectorImpl<char> *RealPath) {
649   SmallString<128> Storage;
650   StringRef P = Name.toNullTerminatedStringRef(Storage);
651   int OpenFlags = O_RDONLY;
652 #ifdef O_CLOEXEC
653   OpenFlags |= O_CLOEXEC;
654 #endif
655   while ((ResultFD = open(P.begin(), OpenFlags)) < 0) {
656     if (errno != EINTR)
657       return std::error_code(errno, std::generic_category());
658   }
659 #ifndef O_CLOEXEC
660   int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
661   (void)r;
662   assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
663 #endif
664   // Attempt to get the real name of the file, if the user asked
665   if(!RealPath)
666     return std::error_code();
667   RealPath->clear();
668 #if defined(F_GETPATH)
669   // When F_GETPATH is availble, it is the quickest way to get
670   // the real path name.
671   char Buffer[MAXPATHLEN];
672   if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
673     RealPath->append(Buffer, Buffer + strlen(Buffer));
674 #else
675   char Buffer[PATH_MAX];
676   if (hasProcSelfFD()) {
677     char ProcPath[64];
678     snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
679     ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
680     if (CharCount > 0)
681       RealPath->append(Buffer, Buffer + CharCount);
682   } else {
683     // Use ::realpath to get the real path name
684     if (::realpath(P.begin(), Buffer) != nullptr)
685       RealPath->append(Buffer, Buffer + strlen(Buffer));
686   }
687 #endif
688   return std::error_code();
689 }
690
691 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
692                             sys::fs::OpenFlags Flags, unsigned Mode) {
693   // Verify that we don't have both "append" and "excl".
694   assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
695          "Cannot specify both 'excl' and 'append' file creation flags!");
696
697   int OpenFlags = O_CREAT;
698
699 #ifdef O_CLOEXEC
700   OpenFlags |= O_CLOEXEC;
701 #endif
702
703   if (Flags & F_RW)
704     OpenFlags |= O_RDWR;
705   else
706     OpenFlags |= O_WRONLY;
707
708   if (Flags & F_Append)
709     OpenFlags |= O_APPEND;
710   else
711     OpenFlags |= O_TRUNC;
712
713   if (Flags & F_Excl)
714     OpenFlags |= O_EXCL;
715
716   SmallString<128> Storage;
717   StringRef P = Name.toNullTerminatedStringRef(Storage);
718   while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
719     if (errno != EINTR)
720       return std::error_code(errno, std::generic_category());
721   }
722 #ifndef O_CLOEXEC
723   int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
724   (void)r;
725   assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
726 #endif
727   return std::error_code();
728 }
729
730 std::error_code getPathFromOpenFD(int FD, SmallVectorImpl<char> &ResultPath) {
731   if (FD < 0)
732     return make_error_code(errc::bad_file_descriptor);
733
734 #if defined(F_GETPATH)
735   // When F_GETPATH is availble, it is the quickest way to get
736   // the path from a file descriptor.
737   ResultPath.reserve(MAXPATHLEN);
738   if (::fcntl(FD, F_GETPATH, ResultPath.begin()) == -1)
739     return std::error_code(errno, std::generic_category());
740
741   ResultPath.set_size(strlen(ResultPath.begin()));
742 #else
743   // If we have a /proc filesystem mounted, we can quickly establish the
744   // real name of the file with readlink. Otherwise, we don't know how to
745   // get the filename from a file descriptor. Give up.
746   if (!fs::hasProcSelfFD())
747     return make_error_code(errc::function_not_supported);
748
749   ResultPath.reserve(PATH_MAX);
750   char ProcPath[64];
751   snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", FD);
752   ssize_t CharCount = ::readlink(ProcPath, ResultPath.begin(), ResultPath.capacity());
753   if (CharCount < 0)
754       return std::error_code(errno, std::generic_category());
755
756   // Was the filename truncated?
757   if (static_cast<size_t>(CharCount) == ResultPath.capacity()) {
758     // Use lstat to get the size of the filename
759     struct stat sb;
760     if (::lstat(ProcPath, &sb) < 0)
761       return std::error_code(errno, std::generic_category());
762
763     ResultPath.reserve(sb.st_size + 1);
764     CharCount = ::readlink(ProcPath, ResultPath.begin(), ResultPath.capacity());
765     if (CharCount < 0)
766       return std::error_code(errno, std::generic_category());
767
768     // Test for race condition: did the link size change?
769     if (CharCount > sb.st_size)
770       return std::error_code(ENAMETOOLONG, std::generic_category());
771   }
772   ResultPath.set_size(static_cast<size_t>(CharCount));
773 #endif
774   return std::error_code();
775 }
776
777 } // end namespace fs
778
779 namespace path {
780
781 bool home_directory(SmallVectorImpl<char> &result) {
782   if (char *RequestedDir = getenv("HOME")) {
783     result.clear();
784     result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
785     return true;
786   }
787
788   return false;
789 }
790
791 static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
792   #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
793   // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
794   // macros defined in <unistd.h> on darwin >= 9
795   int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
796                          : _CS_DARWIN_USER_CACHE_DIR;
797   size_t ConfLen = confstr(ConfName, nullptr, 0);
798   if (ConfLen > 0) {
799     do {
800       Result.resize(ConfLen);
801       ConfLen = confstr(ConfName, Result.data(), Result.size());
802     } while (ConfLen > 0 && ConfLen != Result.size());
803
804     if (ConfLen > 0) {
805       assert(Result.back() == 0);
806       Result.pop_back();
807       return true;
808     }
809
810     Result.clear();
811   }
812   #endif
813   return false;
814 }
815
816 static bool getUserCacheDir(SmallVectorImpl<char> &Result) {
817   // First try using XDG_CACHE_HOME env variable,
818   // as specified in XDG Base Directory Specification at
819   // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
820   if (const char *XdgCacheDir = std::getenv("XDG_CACHE_HOME")) {
821     Result.clear();
822     Result.append(XdgCacheDir, XdgCacheDir + strlen(XdgCacheDir));
823     return true;
824   }
825
826   // Try Darwin configuration query
827   if (getDarwinConfDir(false, Result))
828     return true;
829
830   // Use "$HOME/.cache" if $HOME is available
831   if (home_directory(Result)) {
832     append(Result, ".cache");
833     return true;
834   }
835
836   return false;
837 }
838
839 static const char *getEnvTempDir() {
840   // Check whether the temporary directory is specified by an environment
841   // variable.
842   const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
843   for (const char *Env : EnvironmentVariables) {
844     if (const char *Dir = std::getenv(Env))
845       return Dir;
846   }
847
848   return nullptr;
849 }
850
851 static const char *getDefaultTempDir(bool ErasedOnReboot) {
852 #ifdef P_tmpdir
853   if ((bool)P_tmpdir)
854     return P_tmpdir;
855 #endif
856
857   if (ErasedOnReboot)
858     return "/tmp";
859   return "/var/tmp";
860 }
861
862 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
863   Result.clear();
864
865   if (ErasedOnReboot) {
866     // There is no env variable for the cache directory.
867     if (const char *RequestedDir = getEnvTempDir()) {
868       Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
869       return;
870     }
871   }
872
873   if (getDarwinConfDir(ErasedOnReboot, Result))
874     return;
875
876   const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
877   Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
878 }
879
880 } // end namespace path
881
882 } // end namespace sys
883 } // end namespace llvm