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_SYS_MMAN_H
29#include <sys/mman.h>
30#endif
31#if HAVE_DIRENT_H
32# include <dirent.h>
33# define NAMLEN(dirent) strlen((dirent)->d_name)
34#else
35# define dirent direct
36# define NAMLEN(dirent) (dirent)->d_namlen
37# if HAVE_SYS_NDIR_H
38#  include <sys/ndir.h>
39# endif
40# if HAVE_SYS_DIR_H
41#  include <sys/dir.h>
42# endif
43# if HAVE_NDIR_H
44#  include <ndir.h>
45# endif
46#endif
47
48#ifdef __APPLE__
49#include <mach-o/dyld.h>
50#endif
51
52// Both stdio.h and cstdio are included via different pathes and
53// stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
54// either.
55#undef ferror
56#undef feof
57
58// For GNU Hurd
59#if defined(__GNU__) && !defined(PATH_MAX)
60# define PATH_MAX 4096
61#endif
62
63using namespace llvm;
64
65namespace {
66  /// This class automatically closes the given file descriptor when it goes out
67  /// of scope. You can take back explicit ownership of the file descriptor by
68  /// calling take(). The destructor does not verify that close was successful.
69  /// Therefore, never allow this class to call close on a file descriptor that
70  /// has been read from or written to.
71  struct AutoFD {
72    int FileDescriptor;
73
74    AutoFD(int fd) : FileDescriptor(fd) {}
75    ~AutoFD() {
76      if (FileDescriptor >= 0)
77        ::close(FileDescriptor);
78    }
79
80    int take() {
81      int ret = FileDescriptor;
82      FileDescriptor = -1;
83      return ret;
84    }
85
86    operator int() const {return FileDescriptor;}
87  };
88}
89
90static error_code TempDir(SmallVectorImpl<char> &result) {
91  // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
92  const char *dir = 0;
93  (dir = std::getenv("TMPDIR")) || (dir = std::getenv("TMP")) ||
94      (dir = std::getenv("TEMP")) || (dir = std::getenv("TEMPDIR")) ||
95#ifdef P_tmpdir
96      (dir = P_tmpdir) ||
97#endif
98      (dir = "/tmp");
99
100  result.clear();
101  StringRef d(dir);
102  result.append(d.begin(), d.end());
103  return error_code::success();
104}
105
106namespace llvm {
107namespace sys  {
108namespace fs {
109#if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
110    defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
111    defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
112static int
113test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
114{
115  struct stat sb;
116  char fullpath[PATH_MAX];
117
118  snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
119  if (realpath(fullpath, ret) == NULL)
120    return (1);
121  if (stat(fullpath, &sb) != 0)
122    return (1);
123
124  return (0);
125}
126
127static char *
128getprogpath(char ret[PATH_MAX], const char *bin)
129{
130  char *pv, *s, *t;
131
132  /* First approach: absolute path. */
133  if (bin[0] == '/') {
134    if (test_dir(ret, "/", bin) == 0)
135      return (ret);
136    return (NULL);
137  }
138
139  /* Second approach: relative path. */
140  if (strchr(bin, '/') != NULL) {
141    char cwd[PATH_MAX];
142    if (getcwd(cwd, PATH_MAX) == NULL)
143      return (NULL);
144    if (test_dir(ret, cwd, bin) == 0)
145      return (ret);
146    return (NULL);
147  }
148
149  /* Third approach: $PATH */
150  if ((pv = getenv("PATH")) == NULL)
151    return (NULL);
152  s = pv = strdup(pv);
153  if (pv == NULL)
154    return (NULL);
155  while ((t = strsep(&s, ":")) != NULL) {
156    if (test_dir(ret, t, bin) == 0) {
157      free(pv);
158      return (ret);
159    }
160  }
161  free(pv);
162  return (NULL);
163}
164#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
165
166/// GetMainExecutable - Return the path to the main executable, given the
167/// value of argv[0] from program startup.
168std::string getMainExecutable(const char *argv0, void *MainAddr) {
169#if defined(__APPLE__)
170  // On OS X the executable path is saved to the stack by dyld. Reading it
171  // from there is much faster than calling dladdr, especially for large
172  // binaries with symbols.
173  char exe_path[MAXPATHLEN];
174  uint32_t size = sizeof(exe_path);
175  if (_NSGetExecutablePath(exe_path, &size) == 0) {
176    char link_path[MAXPATHLEN];
177    if (realpath(exe_path, link_path))
178      return link_path;
179  }
180#elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
181      defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
182      defined(__FreeBSD_kernel__)
183  char exe_path[PATH_MAX];
184
185  if (getprogpath(exe_path, argv0) != NULL)
186    return exe_path;
187#elif defined(__linux__) || defined(__CYGWIN__)
188  char exe_path[MAXPATHLEN];
189  StringRef aPath("/proc/self/exe");
190  if (sys::fs::exists(aPath)) {
191      // /proc is not always mounted under Linux (chroot for example).
192      ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
193      if (len >= 0)
194          return StringRef(exe_path, len);
195  } else {
196      // Fall back to the classical detection.
197      if (getprogpath(exe_path, argv0) != NULL)
198          return exe_path;
199  }
200#elif defined(HAVE_DLFCN_H)
201  // Use dladdr to get executable path if available.
202  Dl_info DLInfo;
203  int err = dladdr(MainAddr, &DLInfo);
204  if (err == 0)
205    return "";
206
207  // If the filename is a symlink, we need to resolve and return the location of
208  // the actual executable.
209  char link_path[MAXPATHLEN];
210  if (realpath(DLInfo.dli_fname, link_path))
211    return link_path;
212#else
213#error GetMainExecutable is not implemented on this host yet.
214#endif
215  return "";
216}
217
218TimeValue file_status::getLastModificationTime() const {
219  TimeValue Ret;
220  Ret.fromEpochTime(fs_st_mtime);
221  return Ret;
222}
223
224UniqueID file_status::getUniqueID() const {
225  return UniqueID(fs_st_dev, fs_st_ino);
226}
227
228error_code current_path(SmallVectorImpl<char> &result) {
229  result.clear();
230
231  const char *pwd = ::getenv("PWD");
232  llvm::sys::fs::file_status PWDStatus, DotStatus;
233  if (pwd && llvm::sys::path::is_absolute(pwd) &&
234      !llvm::sys::fs::status(pwd, PWDStatus) &&
235      !llvm::sys::fs::status(".", DotStatus) &&
236      PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
237    result.append(pwd, pwd + strlen(pwd));
238    return error_code::success();
239  }
240
241#ifdef MAXPATHLEN
242  result.reserve(MAXPATHLEN);
243#else
244// For GNU Hurd
245  result.reserve(1024);
246#endif
247
248  while (true) {
249    if (::getcwd(result.data(), result.capacity()) == 0) {
250      // See if there was a real error.
251      if (errno != errc::not_enough_memory)
252        return error_code(errno, system_category());
253      // Otherwise there just wasn't enough space.
254      result.reserve(result.capacity() * 2);
255    } else
256      break;
257  }
258
259  result.set_size(strlen(result.data()));
260  return error_code::success();
261}
262
263error_code create_directory(const Twine &path, bool IgnoreExisting) {
264  SmallString<128> path_storage;
265  StringRef p = path.toNullTerminatedStringRef(path_storage);
266
267  if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
268    if (errno != errc::file_exists || !IgnoreExisting)
269      return error_code(errno, system_category());
270  }
271
272  return error_code::success();
273}
274
275error_code create_hard_link(const Twine &to, const Twine &from) {
276  // Get arguments.
277  SmallString<128> from_storage;
278  SmallString<128> to_storage;
279  StringRef f = from.toNullTerminatedStringRef(from_storage);
280  StringRef t = to.toNullTerminatedStringRef(to_storage);
281
282  if (::link(t.begin(), f.begin()) == -1)
283    return error_code(errno, system_category());
284
285  return error_code::success();
286}
287
288error_code remove(const Twine &path, bool IgnoreNonExisting) {
289  SmallString<128> path_storage;
290  StringRef p = path.toNullTerminatedStringRef(path_storage);
291
292  struct stat buf;
293  if (stat(p.begin(), &buf) != 0) {
294    if (errno != errc::no_such_file_or_directory || !IgnoreNonExisting)
295      return error_code(errno, system_category());
296    return error_code::success();
297  }
298
299  // Note: this check catches strange situations. In all cases, LLVM should
300  // only be involved in the creation and deletion of regular files.  This
301  // check ensures that what we're trying to erase is a regular file. It
302  // effectively prevents LLVM from erasing things like /dev/null, any block
303  // special file, or other things that aren't "regular" files.
304  if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
305    return make_error_code(errc::operation_not_permitted);
306
307  if (::remove(p.begin()) == -1) {
308    if (errno != errc::no_such_file_or_directory || !IgnoreNonExisting)
309      return error_code(errno, system_category());
310  }
311
312  return error_code::success();
313}
314
315error_code rename(const Twine &from, const Twine &to) {
316  // Get arguments.
317  SmallString<128> from_storage;
318  SmallString<128> to_storage;
319  StringRef f = from.toNullTerminatedStringRef(from_storage);
320  StringRef t = to.toNullTerminatedStringRef(to_storage);
321
322  if (::rename(f.begin(), t.begin()) == -1)
323    return error_code(errno, system_category());
324
325  return error_code::success();
326}
327
328error_code resize_file(const Twine &path, uint64_t size) {
329  SmallString<128> path_storage;
330  StringRef p = path.toNullTerminatedStringRef(path_storage);
331
332  if (::truncate(p.begin(), size) == -1)
333    return error_code(errno, system_category());
334
335  return error_code::success();
336}
337
338error_code exists(const Twine &path, bool &result) {
339  SmallString<128> path_storage;
340  StringRef p = path.toNullTerminatedStringRef(path_storage);
341
342  if (::access(p.begin(), F_OK) == -1) {
343    if (errno != errc::no_such_file_or_directory)
344      return error_code(errno, system_category());
345    result = false;
346  } else
347    result = true;
348
349  return error_code::success();
350}
351
352bool can_write(const Twine &Path) {
353  SmallString<128> PathStorage;
354  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
355  return 0 == access(P.begin(), W_OK);
356}
357
358bool can_execute(const Twine &Path) {
359  SmallString<128> PathStorage;
360  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
361
362  if (0 != access(P.begin(), R_OK | X_OK))
363    return false;
364  struct stat buf;
365  if (0 != stat(P.begin(), &buf))
366    return false;
367  if (!S_ISREG(buf.st_mode))
368    return false;
369  return true;
370}
371
372bool equivalent(file_status A, file_status B) {
373  assert(status_known(A) && status_known(B));
374  return A.fs_st_dev == B.fs_st_dev &&
375         A.fs_st_ino == B.fs_st_ino;
376}
377
378error_code equivalent(const Twine &A, const Twine &B, bool &result) {
379  file_status fsA, fsB;
380  if (error_code ec = status(A, fsA)) return ec;
381  if (error_code ec = status(B, fsB)) return ec;
382  result = equivalent(fsA, fsB);
383  return error_code::success();
384}
385
386static error_code fillStatus(int StatRet, const struct stat &Status,
387                             file_status &Result) {
388  if (StatRet != 0) {
389    error_code ec(errno, system_category());
390    if (ec == errc::no_such_file_or_directory)
391      Result = file_status(file_type::file_not_found);
392    else
393      Result = file_status(file_type::status_error);
394    return ec;
395  }
396
397  file_type Type = file_type::type_unknown;
398
399  if (S_ISDIR(Status.st_mode))
400    Type = file_type::directory_file;
401  else if (S_ISREG(Status.st_mode))
402    Type = file_type::regular_file;
403  else if (S_ISBLK(Status.st_mode))
404    Type = file_type::block_file;
405  else if (S_ISCHR(Status.st_mode))
406    Type = file_type::character_file;
407  else if (S_ISFIFO(Status.st_mode))
408    Type = file_type::fifo_file;
409  else if (S_ISSOCK(Status.st_mode))
410    Type = file_type::socket_file;
411
412  perms Perms = static_cast<perms>(Status.st_mode);
413  Result =
414      file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
415                  Status.st_uid, Status.st_gid, Status.st_size);
416
417  return error_code::success();
418}
419
420error_code status(const Twine &Path, file_status &Result) {
421  SmallString<128> PathStorage;
422  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
423
424  struct stat Status;
425  int StatRet = ::stat(P.begin(), &Status);
426  return fillStatus(StatRet, Status, Result);
427}
428
429error_code status(int FD, file_status &Result) {
430  struct stat Status;
431  int StatRet = ::fstat(FD, &Status);
432  return fillStatus(StatRet, Status, Result);
433}
434
435error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
436#if defined(HAVE_FUTIMENS)
437  timespec Times[2];
438  Times[0].tv_sec = Time.toEpochTime();
439  Times[0].tv_nsec = 0;
440  Times[1] = Times[0];
441  if (::futimens(FD, Times))
442    return error_code(errno, system_category());
443  return error_code::success();
444#elif defined(HAVE_FUTIMES)
445  timeval Times[2];
446  Times[0].tv_sec = Time.toEpochTime();
447  Times[0].tv_usec = 0;
448  Times[1] = Times[0];
449  if (::futimes(FD, Times))
450    return error_code(errno, system_category());
451  return error_code::success();
452#else
453#warning Missing futimes() and futimens()
454  return make_error_code(errc::not_supported);
455#endif
456}
457
458error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
459  AutoFD ScopedFD(FD);
460  if (!CloseFD)
461    ScopedFD.take();
462
463  // Figure out how large the file is.
464  struct stat FileInfo;
465  if (fstat(FD, &FileInfo) == -1)
466    return error_code(errno, system_category());
467  uint64_t FileSize = FileInfo.st_size;
468
469  if (Size == 0)
470    Size = FileSize;
471  else if (FileSize < Size) {
472    // We need to grow the file.
473    if (ftruncate(FD, Size) == -1)
474      return error_code(errno, system_category());
475  }
476
477  int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
478  int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
479#ifdef MAP_FILE
480  flags |= MAP_FILE;
481#endif
482  Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
483  if (Mapping == MAP_FAILED)
484    return error_code(errno, system_category());
485  return error_code::success();
486}
487
488mapped_file_region::mapped_file_region(const Twine &path,
489                                       mapmode mode,
490                                       uint64_t length,
491                                       uint64_t offset,
492                                       error_code &ec)
493  : Mode(mode)
494  , Size(length)
495  , Mapping() {
496  // Make sure that the requested size fits within SIZE_T.
497  if (length > std::numeric_limits<size_t>::max()) {
498    ec = make_error_code(errc::invalid_argument);
499    return;
500  }
501
502  SmallString<128> path_storage;
503  StringRef name = path.toNullTerminatedStringRef(path_storage);
504  int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
505  int ofd = ::open(name.begin(), oflags);
506  if (ofd == -1) {
507    ec = error_code(errno, system_category());
508    return;
509  }
510
511  ec = init(ofd, true, offset);
512  if (ec)
513    Mapping = 0;
514}
515
516mapped_file_region::mapped_file_region(int fd,
517                                       bool closefd,
518                                       mapmode mode,
519                                       uint64_t length,
520                                       uint64_t offset,
521                                       error_code &ec)
522  : Mode(mode)
523  , Size(length)
524  , Mapping() {
525  // Make sure that the requested size fits within SIZE_T.
526  if (length > std::numeric_limits<size_t>::max()) {
527    ec = make_error_code(errc::invalid_argument);
528    return;
529  }
530
531  ec = init(fd, closefd, offset);
532  if (ec)
533    Mapping = 0;
534}
535
536mapped_file_region::~mapped_file_region() {
537  if (Mapping)
538    ::munmap(Mapping, Size);
539}
540
541#if LLVM_HAS_RVALUE_REFERENCES
542mapped_file_region::mapped_file_region(mapped_file_region &&other)
543  : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
544  other.Mapping = 0;
545}
546#endif
547
548mapped_file_region::mapmode mapped_file_region::flags() const {
549  assert(Mapping && "Mapping failed but used anyway!");
550  return Mode;
551}
552
553uint64_t mapped_file_region::size() const {
554  assert(Mapping && "Mapping failed but used anyway!");
555  return Size;
556}
557
558char *mapped_file_region::data() const {
559  assert(Mapping && "Mapping failed but used anyway!");
560  assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
561  return reinterpret_cast<char*>(Mapping);
562}
563
564const char *mapped_file_region::const_data() const {
565  assert(Mapping && "Mapping failed but used anyway!");
566  return reinterpret_cast<const char*>(Mapping);
567}
568
569int mapped_file_region::alignment() {
570  return process::get_self()->page_size();
571}
572
573error_code detail::directory_iterator_construct(detail::DirIterState &it,
574                                                StringRef path){
575  SmallString<128> path_null(path);
576  DIR *directory = ::opendir(path_null.c_str());
577  if (directory == 0)
578    return error_code(errno, system_category());
579
580  it.IterationHandle = reinterpret_cast<intptr_t>(directory);
581  // Add something for replace_filename to replace.
582  path::append(path_null, ".");
583  it.CurrentEntry = directory_entry(path_null.str());
584  return directory_iterator_increment(it);
585}
586
587error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
588  if (it.IterationHandle)
589    ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
590  it.IterationHandle = 0;
591  it.CurrentEntry = directory_entry();
592  return error_code::success();
593}
594
595error_code detail::directory_iterator_increment(detail::DirIterState &it) {
596  errno = 0;
597  dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
598  if (cur_dir == 0 && errno != 0) {
599    return error_code(errno, system_category());
600  } else if (cur_dir != 0) {
601    StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
602    if ((name.size() == 1 && name[0] == '.') ||
603        (name.size() == 2 && name[0] == '.' && name[1] == '.'))
604      return directory_iterator_increment(it);
605    it.CurrentEntry.replace_filename(name);
606  } else
607    return directory_iterator_destruct(it);
608
609  return error_code::success();
610}
611
612error_code get_magic(const Twine &path, uint32_t len,
613                     SmallVectorImpl<char> &result) {
614  SmallString<128> PathStorage;
615  StringRef Path = path.toNullTerminatedStringRef(PathStorage);
616  result.set_size(0);
617
618  // Open path.
619  std::FILE *file = std::fopen(Path.data(), "rb");
620  if (file == 0)
621    return error_code(errno, system_category());
622
623  // Reserve storage.
624  result.reserve(len);
625
626  // Read magic!
627  size_t size = std::fread(result.data(), 1, len, file);
628  if (std::ferror(file) != 0) {
629    std::fclose(file);
630    return error_code(errno, system_category());
631  } else if (size != len) {
632    if (std::feof(file) != 0) {
633      std::fclose(file);
634      result.set_size(size);
635      return make_error_code(errc::value_too_large);
636    }
637  }
638  std::fclose(file);
639  result.set_size(size);
640  return error_code::success();
641}
642
643error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
644                                            bool map_writable, void *&result) {
645  SmallString<128> path_storage;
646  StringRef name = path.toNullTerminatedStringRef(path_storage);
647  int oflags = map_writable ? O_RDWR : O_RDONLY;
648  int ofd = ::open(name.begin(), oflags);
649  if ( ofd == -1 )
650    return error_code(errno, system_category());
651  AutoFD fd(ofd);
652  int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
653  int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
654#ifdef MAP_FILE
655  flags |= MAP_FILE;
656#endif
657  result = ::mmap(0, size, prot, flags, fd, file_offset);
658  if (result == MAP_FAILED) {
659    return error_code(errno, system_category());
660  }
661
662  return error_code::success();
663}
664
665error_code unmap_file_pages(void *base, size_t size) {
666  if ( ::munmap(base, size) == -1 )
667    return error_code(errno, system_category());
668
669  return error_code::success();
670}
671
672error_code openFileForRead(const Twine &Name, int &ResultFD) {
673  SmallString<128> Storage;
674  StringRef P = Name.toNullTerminatedStringRef(Storage);
675  while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
676    if (errno != EINTR)
677      return error_code(errno, system_category());
678  }
679  return error_code::success();
680}
681
682error_code openFileForWrite(const Twine &Name, int &ResultFD,
683                            sys::fs::OpenFlags Flags, unsigned Mode) {
684  // Verify that we don't have both "append" and "excl".
685  assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
686         "Cannot specify both 'excl' and 'append' file creation flags!");
687
688  int OpenFlags = O_CREAT;
689
690  if (Flags & F_RW)
691    OpenFlags |= O_RDWR;
692  else
693    OpenFlags |= O_WRONLY;
694
695  if (Flags & F_Append)
696    OpenFlags |= O_APPEND;
697  else
698    OpenFlags |= O_TRUNC;
699
700  if (Flags & F_Excl)
701    OpenFlags |= O_EXCL;
702
703  SmallString<128> Storage;
704  StringRef P = Name.toNullTerminatedStringRef(Storage);
705  while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
706    if (errno != EINTR)
707      return error_code(errno, system_category());
708  }
709  return error_code::success();
710}
711
712} // end namespace fs
713
714namespace path {
715
716bool home_directory(SmallVectorImpl<char> &result) {
717  if (char *RequestedDir = getenv("HOME")) {
718    result.clear();
719    result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
720    return true;
721  }
722
723  return false;
724}
725
726} // end namespace path
727
728} // end namespace sys
729} // end namespace llvm
730