• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 llvm {
66namespace sys  {
67namespace fs {
68#if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
69    defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
70    defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
71static int
72test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
73{
74  struct stat sb;
75  char fullpath[PATH_MAX];
76
77  snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
78  if (!realpath(fullpath, ret))
79    return 1;
80  if (stat(fullpath, &sb) != 0)
81    return 1;
82
83  return 0;
84}
85
86static char *
87getprogpath(char ret[PATH_MAX], const char *bin)
88{
89  char *pv, *s, *t;
90
91  /* First approach: absolute path. */
92  if (bin[0] == '/') {
93    if (test_dir(ret, "/", bin) == 0)
94      return ret;
95    return nullptr;
96  }
97
98  /* Second approach: relative path. */
99  if (strchr(bin, '/')) {
100    char cwd[PATH_MAX];
101    if (!getcwd(cwd, PATH_MAX))
102      return nullptr;
103    if (test_dir(ret, cwd, bin) == 0)
104      return ret;
105    return nullptr;
106  }
107
108  /* Third approach: $PATH */
109  if ((pv = getenv("PATH")) == nullptr)
110    return nullptr;
111  s = pv = strdup(pv);
112  if (!pv)
113    return nullptr;
114  while ((t = strsep(&s, ":")) != nullptr) {
115    if (test_dir(ret, t, bin) == 0) {
116      free(pv);
117      return ret;
118    }
119  }
120  free(pv);
121  return nullptr;
122}
123#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
124
125/// GetMainExecutable - Return the path to the main executable, given the
126/// value of argv[0] from program startup.
127std::string getMainExecutable(const char *argv0, void *MainAddr) {
128#if defined(__APPLE__)
129  // On OS X the executable path is saved to the stack by dyld. Reading it
130  // from there is much faster than calling dladdr, especially for large
131  // binaries with symbols.
132  char exe_path[MAXPATHLEN];
133  uint32_t size = sizeof(exe_path);
134  if (_NSGetExecutablePath(exe_path, &size) == 0) {
135    char link_path[MAXPATHLEN];
136    if (realpath(exe_path, link_path))
137      return link_path;
138  }
139#elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
140      defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
141      defined(__FreeBSD_kernel__)
142  char exe_path[PATH_MAX];
143
144  if (getprogpath(exe_path, argv0) != NULL)
145    return exe_path;
146#elif defined(__linux__) || defined(__CYGWIN__)
147  char exe_path[MAXPATHLEN];
148  StringRef aPath("/proc/self/exe");
149  if (sys::fs::exists(aPath)) {
150      // /proc is not always mounted under Linux (chroot for example).
151      ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
152      if (len >= 0)
153          return std::string(exe_path, len);
154  } else {
155      // Fall back to the classical detection.
156      if (getprogpath(exe_path, argv0))
157        return exe_path;
158  }
159#elif defined(HAVE_DLFCN_H)
160  // Use dladdr to get executable path if available.
161  Dl_info DLInfo;
162  int err = dladdr(MainAddr, &DLInfo);
163  if (err == 0)
164    return "";
165
166  // If the filename is a symlink, we need to resolve and return the location of
167  // the actual executable.
168  char link_path[MAXPATHLEN];
169  if (realpath(DLInfo.dli_fname, link_path))
170    return link_path;
171#else
172#error GetMainExecutable is not implemented on this host yet.
173#endif
174  return "";
175}
176
177TimeValue file_status::getLastModificationTime() const {
178  TimeValue Ret;
179  Ret.fromEpochTime(fs_st_mtime);
180  return Ret;
181}
182
183UniqueID file_status::getUniqueID() const {
184  return UniqueID(fs_st_dev, fs_st_ino);
185}
186
187std::error_code current_path(SmallVectorImpl<char> &result) {
188  result.clear();
189
190  const char *pwd = ::getenv("PWD");
191  llvm::sys::fs::file_status PWDStatus, DotStatus;
192  if (pwd && llvm::sys::path::is_absolute(pwd) &&
193      !llvm::sys::fs::status(pwd, PWDStatus) &&
194      !llvm::sys::fs::status(".", DotStatus) &&
195      PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
196    result.append(pwd, pwd + strlen(pwd));
197    return std::error_code();
198  }
199
200#ifdef MAXPATHLEN
201  result.reserve(MAXPATHLEN);
202#else
203// For GNU Hurd
204  result.reserve(1024);
205#endif
206
207  while (true) {
208    if (::getcwd(result.data(), result.capacity()) == nullptr) {
209      // See if there was a real error.
210      if (errno != ENOMEM)
211        return std::error_code(errno, std::generic_category());
212      // Otherwise there just wasn't enough space.
213      result.reserve(result.capacity() * 2);
214    } else
215      break;
216  }
217
218  result.set_size(strlen(result.data()));
219  return std::error_code();
220}
221
222std::error_code create_directory(const Twine &path, bool IgnoreExisting,
223                                 perms Perms) {
224  SmallString<128> path_storage;
225  StringRef p = path.toNullTerminatedStringRef(path_storage);
226
227  if (::mkdir(p.begin(), Perms) == -1) {
228    if (errno != EEXIST || !IgnoreExisting)
229      return std::error_code(errno, std::generic_category());
230  }
231
232  return std::error_code();
233}
234
235// Note that we are using symbolic link because hard links are not supported by
236// all filesystems (SMB doesn't).
237std::error_code create_link(const Twine &to, const Twine &from) {
238  // Get arguments.
239  SmallString<128> from_storage;
240  SmallString<128> to_storage;
241  StringRef f = from.toNullTerminatedStringRef(from_storage);
242  StringRef t = to.toNullTerminatedStringRef(to_storage);
243
244  if (::symlink(t.begin(), f.begin()) == -1)
245    return std::error_code(errno, std::generic_category());
246
247  return std::error_code();
248}
249
250std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
251  SmallString<128> path_storage;
252  StringRef p = path.toNullTerminatedStringRef(path_storage);
253
254  struct stat buf;
255  if (lstat(p.begin(), &buf) != 0) {
256    if (errno != ENOENT || !IgnoreNonExisting)
257      return std::error_code(errno, std::generic_category());
258    return std::error_code();
259  }
260
261  // Note: this check catches strange situations. In all cases, LLVM should
262  // only be involved in the creation and deletion of regular files.  This
263  // check ensures that what we're trying to erase is a regular file. It
264  // effectively prevents LLVM from erasing things like /dev/null, any block
265  // special file, or other things that aren't "regular" files.
266  if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
267    return make_error_code(errc::operation_not_permitted);
268
269  if (::remove(p.begin()) == -1) {
270    if (errno != ENOENT || !IgnoreNonExisting)
271      return std::error_code(errno, std::generic_category());
272  }
273
274  return std::error_code();
275}
276
277std::error_code rename(const Twine &from, const Twine &to) {
278  // Get arguments.
279  SmallString<128> from_storage;
280  SmallString<128> to_storage;
281  StringRef f = from.toNullTerminatedStringRef(from_storage);
282  StringRef t = to.toNullTerminatedStringRef(to_storage);
283
284  if (::rename(f.begin(), t.begin()) == -1)
285    return std::error_code(errno, std::generic_category());
286
287  return std::error_code();
288}
289
290std::error_code resize_file(int FD, uint64_t Size) {
291  if (::ftruncate(FD, Size) == -1)
292    return std::error_code(errno, std::generic_category());
293
294  return std::error_code();
295}
296
297static int convertAccessMode(AccessMode Mode) {
298  switch (Mode) {
299  case AccessMode::Exist:
300    return F_OK;
301  case AccessMode::Write:
302    return W_OK;
303  case AccessMode::Execute:
304    return R_OK | X_OK; // scripts also need R_OK.
305  }
306  llvm_unreachable("invalid enum");
307}
308
309std::error_code access(const Twine &Path, AccessMode Mode) {
310  SmallString<128> PathStorage;
311  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
312
313  if (::access(P.begin(), convertAccessMode(Mode)) == -1)
314    return std::error_code(errno, std::generic_category());
315
316  if (Mode == AccessMode::Execute) {
317    // Don't say that directories are executable.
318    struct stat buf;
319    if (0 != stat(P.begin(), &buf))
320      return errc::permission_denied;
321    if (!S_ISREG(buf.st_mode))
322      return errc::permission_denied;
323  }
324
325  return std::error_code();
326}
327
328bool can_execute(const Twine &Path) {
329  return !access(Path, AccessMode::Execute);
330}
331
332bool equivalent(file_status A, file_status B) {
333  assert(status_known(A) && status_known(B));
334  return A.fs_st_dev == B.fs_st_dev &&
335         A.fs_st_ino == B.fs_st_ino;
336}
337
338std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
339  file_status fsA, fsB;
340  if (std::error_code ec = status(A, fsA))
341    return ec;
342  if (std::error_code ec = status(B, fsB))
343    return ec;
344  result = equivalent(fsA, fsB);
345  return std::error_code();
346}
347
348static std::error_code fillStatus(int StatRet, const struct stat &Status,
349                             file_status &Result) {
350  if (StatRet != 0) {
351    std::error_code ec(errno, std::generic_category());
352    if (ec == errc::no_such_file_or_directory)
353      Result = file_status(file_type::file_not_found);
354    else
355      Result = file_status(file_type::status_error);
356    return ec;
357  }
358
359  file_type Type = file_type::type_unknown;
360
361  if (S_ISDIR(Status.st_mode))
362    Type = file_type::directory_file;
363  else if (S_ISREG(Status.st_mode))
364    Type = file_type::regular_file;
365  else if (S_ISBLK(Status.st_mode))
366    Type = file_type::block_file;
367  else if (S_ISCHR(Status.st_mode))
368    Type = file_type::character_file;
369  else if (S_ISFIFO(Status.st_mode))
370    Type = file_type::fifo_file;
371  else if (S_ISSOCK(Status.st_mode))
372    Type = file_type::socket_file;
373
374  perms Perms = static_cast<perms>(Status.st_mode);
375  Result =
376      file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
377                  Status.st_uid, Status.st_gid, Status.st_size);
378
379  return std::error_code();
380}
381
382std::error_code status(const Twine &Path, file_status &Result) {
383  SmallString<128> PathStorage;
384  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
385
386  struct stat Status;
387  int StatRet = ::stat(P.begin(), &Status);
388  return fillStatus(StatRet, Status, Result);
389}
390
391std::error_code status(int FD, file_status &Result) {
392  struct stat Status;
393  int StatRet = ::fstat(FD, &Status);
394  return fillStatus(StatRet, Status, Result);
395}
396
397std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
398#if defined(HAVE_FUTIMENS)
399  timespec Times[2];
400  Times[0].tv_sec = Time.toEpochTime();
401  Times[0].tv_nsec = 0;
402  Times[1] = Times[0];
403  if (::futimens(FD, Times))
404    return std::error_code(errno, std::generic_category());
405  return std::error_code();
406#elif defined(HAVE_FUTIMES)
407  timeval Times[2];
408  Times[0].tv_sec = Time.toEpochTime();
409  Times[0].tv_usec = 0;
410  Times[1] = Times[0];
411  if (::futimes(FD, Times))
412    return std::error_code(errno, std::generic_category());
413  return std::error_code();
414#else
415#warning Missing futimes() and futimens()
416  return make_error_code(errc::function_not_supported);
417#endif
418}
419
420std::error_code mapped_file_region::init(int FD, uint64_t Offset,
421                                         mapmode Mode) {
422  assert(Size != 0);
423
424  int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
425  int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
426  Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
427  if (Mapping == MAP_FAILED)
428    return std::error_code(errno, std::generic_category());
429  return std::error_code();
430}
431
432mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
433                                       uint64_t offset, std::error_code &ec)
434    : Size(length), Mapping() {
435  // Make sure that the requested size fits within SIZE_T.
436  if (length > std::numeric_limits<size_t>::max()) {
437    ec = make_error_code(errc::invalid_argument);
438    return;
439  }
440
441  ec = init(fd, offset, mode);
442  if (ec)
443    Mapping = nullptr;
444}
445
446mapped_file_region::~mapped_file_region() {
447  if (Mapping)
448    ::munmap(Mapping, Size);
449}
450
451uint64_t mapped_file_region::size() const {
452  assert(Mapping && "Mapping failed but used anyway!");
453  return Size;
454}
455
456char *mapped_file_region::data() const {
457  assert(Mapping && "Mapping failed but used anyway!");
458  return reinterpret_cast<char*>(Mapping);
459}
460
461const char *mapped_file_region::const_data() const {
462  assert(Mapping && "Mapping failed but used anyway!");
463  return reinterpret_cast<const char*>(Mapping);
464}
465
466int mapped_file_region::alignment() {
467  return Process::getPageSize();
468}
469
470std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
471                                                StringRef path){
472  SmallString<128> path_null(path);
473  DIR *directory = ::opendir(path_null.c_str());
474  if (!directory)
475    return std::error_code(errno, std::generic_category());
476
477  it.IterationHandle = reinterpret_cast<intptr_t>(directory);
478  // Add something for replace_filename to replace.
479  path::append(path_null, ".");
480  it.CurrentEntry = directory_entry(path_null.str());
481  return directory_iterator_increment(it);
482}
483
484std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
485  if (it.IterationHandle)
486    ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
487  it.IterationHandle = 0;
488  it.CurrentEntry = directory_entry();
489  return std::error_code();
490}
491
492std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
493  errno = 0;
494  dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
495  if (cur_dir == nullptr && errno != 0) {
496    return std::error_code(errno, std::generic_category());
497  } else if (cur_dir != nullptr) {
498    StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
499    if ((name.size() == 1 && name[0] == '.') ||
500        (name.size() == 2 && name[0] == '.' && name[1] == '.'))
501      return directory_iterator_increment(it);
502    it.CurrentEntry.replace_filename(name);
503  } else
504    return directory_iterator_destruct(it);
505
506  return std::error_code();
507}
508
509std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
510  SmallString<128> Storage;
511  StringRef P = Name.toNullTerminatedStringRef(Storage);
512  while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
513    if (errno != EINTR)
514      return std::error_code(errno, std::generic_category());
515  }
516  return std::error_code();
517}
518
519std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
520                            sys::fs::OpenFlags Flags, unsigned Mode) {
521  // Verify that we don't have both "append" and "excl".
522  assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
523         "Cannot specify both 'excl' and 'append' file creation flags!");
524
525  int OpenFlags = O_CREAT;
526
527  if (Flags & F_RW)
528    OpenFlags |= O_RDWR;
529  else
530    OpenFlags |= O_WRONLY;
531
532  if (Flags & F_Append)
533    OpenFlags |= O_APPEND;
534  else
535    OpenFlags |= O_TRUNC;
536
537  if (Flags & F_Excl)
538    OpenFlags |= O_EXCL;
539
540  SmallString<128> Storage;
541  StringRef P = Name.toNullTerminatedStringRef(Storage);
542  while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
543    if (errno != EINTR)
544      return std::error_code(errno, std::generic_category());
545  }
546  return std::error_code();
547}
548
549} // end namespace fs
550
551namespace path {
552
553bool home_directory(SmallVectorImpl<char> &result) {
554  if (char *RequestedDir = getenv("HOME")) {
555    result.clear();
556    result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
557    return true;
558  }
559
560  return false;
561}
562
563static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
564  #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
565  // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
566  // macros defined in <unistd.h> on darwin >= 9
567  int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
568                         : _CS_DARWIN_USER_CACHE_DIR;
569  size_t ConfLen = confstr(ConfName, nullptr, 0);
570  if (ConfLen > 0) {
571    do {
572      Result.resize(ConfLen);
573      ConfLen = confstr(ConfName, Result.data(), Result.size());
574    } while (ConfLen > 0 && ConfLen != Result.size());
575
576    if (ConfLen > 0) {
577      assert(Result.back() == 0);
578      Result.pop_back();
579      return true;
580    }
581
582    Result.clear();
583  }
584  #endif
585  return false;
586}
587
588static bool getUserCacheDir(SmallVectorImpl<char> &Result) {
589  // First try using XDS_CACHE_HOME env variable,
590  // as specified in XDG Base Directory Specification at
591  // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
592  if (const char *XdsCacheDir = std::getenv("XDS_CACHE_HOME")) {
593    Result.clear();
594    Result.append(XdsCacheDir, XdsCacheDir + strlen(XdsCacheDir));
595    return true;
596  }
597
598  // Try Darwin configuration query
599  if (getDarwinConfDir(false, Result))
600    return true;
601
602  // Use "$HOME/.cache" if $HOME is available
603  if (home_directory(Result)) {
604    append(Result, ".cache");
605    return true;
606  }
607
608  return false;
609}
610
611static const char *getEnvTempDir() {
612  // Check whether the temporary directory is specified by an environment
613  // variable.
614  const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
615  for (const char *Env : EnvironmentVariables) {
616    if (const char *Dir = std::getenv(Env))
617      return Dir;
618  }
619
620  return nullptr;
621}
622
623static const char *getDefaultTempDir(bool ErasedOnReboot) {
624#ifdef P_tmpdir
625  if ((bool)P_tmpdir)
626    return P_tmpdir;
627#endif
628
629  if (ErasedOnReboot)
630    return "/tmp";
631  return "/var/tmp";
632}
633
634void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
635  Result.clear();
636
637  if (ErasedOnReboot) {
638    // There is no env variable for the cache directory.
639    if (const char *RequestedDir = getEnvTempDir()) {
640      Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
641      return;
642    }
643  }
644
645  if (getDarwinConfDir(ErasedOnReboot, Result))
646    return;
647
648  const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
649  Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
650}
651
652} // end namespace path
653
654} // end namespace sys
655} // end namespace llvm
656