LLVM API Documentation

Unix/Path.inc
Go to the documentation of this file.
00001 //===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Unix specific implementation of the Path API.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 //===----------------------------------------------------------------------===//
00015 //=== WARNING: Implementation here must contain only generic UNIX code that
00016 //===          is guaranteed to work on *all* UNIX variants.
00017 //===----------------------------------------------------------------------===//
00018 
00019 #include "Unix.h"
00020 #include <limits.h>
00021 #include <stdio.h>
00022 #if HAVE_SYS_STAT_H
00023 #include <sys/stat.h>
00024 #endif
00025 #if HAVE_FCNTL_H
00026 #include <fcntl.h>
00027 #endif
00028 #ifdef HAVE_SYS_MMAN_H
00029 #include <sys/mman.h>
00030 #endif
00031 #if HAVE_DIRENT_H
00032 # include <dirent.h>
00033 # define NAMLEN(dirent) strlen((dirent)->d_name)
00034 #else
00035 # define dirent direct
00036 # define NAMLEN(dirent) (dirent)->d_namlen
00037 # if HAVE_SYS_NDIR_H
00038 #  include <sys/ndir.h>
00039 # endif
00040 # if HAVE_SYS_DIR_H
00041 #  include <sys/dir.h>
00042 # endif
00043 # if HAVE_NDIR_H
00044 #  include <ndir.h>
00045 # endif
00046 #endif
00047 
00048 #ifdef __APPLE__
00049 #include <mach-o/dyld.h>
00050 #endif
00051 
00052 // Both stdio.h and cstdio are included via different pathes and
00053 // stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
00054 // either.
00055 #undef ferror
00056 #undef feof
00057 
00058 // For GNU Hurd
00059 #if defined(__GNU__) && !defined(PATH_MAX)
00060 # define PATH_MAX 4096
00061 #endif
00062 
00063 using namespace llvm;
00064 
00065 namespace llvm {
00066 namespace sys  {
00067 namespace fs {
00068 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
00069     defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
00070     defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
00071 static int
00072 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
00073 {  
00074   struct stat sb;
00075   char fullpath[PATH_MAX];
00076 
00077   snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
00078   if (realpath(fullpath, ret) == NULL)
00079     return (1);
00080   if (stat(fullpath, &sb) != 0)
00081     return (1);
00082 
00083   return (0);
00084 }
00085 
00086 static char *
00087 getprogpath(char ret[PATH_MAX], const char *bin)
00088 {
00089   char *pv, *s, *t;
00090 
00091   /* First approach: absolute path. */
00092   if (bin[0] == '/') {
00093     if (test_dir(ret, "/", bin) == 0)
00094       return (ret);
00095     return (NULL);
00096   }
00097 
00098   /* Second approach: relative path. */
00099   if (strchr(bin, '/') != NULL) {
00100     char cwd[PATH_MAX];
00101     if (getcwd(cwd, PATH_MAX) == NULL)
00102       return (NULL);
00103     if (test_dir(ret, cwd, bin) == 0)
00104       return (ret);
00105     return (NULL);
00106   }
00107 
00108   /* Third approach: $PATH */
00109   if ((pv = getenv("PATH")) == NULL)
00110     return (NULL);
00111   s = pv = strdup(pv);
00112   if (pv == NULL)
00113     return (NULL);
00114   while ((t = strsep(&s, ":")) != NULL) {
00115     if (test_dir(ret, t, bin) == 0) {
00116       free(pv);
00117       return (ret);
00118     }
00119   }
00120   free(pv);
00121   return (NULL);
00122 }
00123 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
00124 
00125 /// GetMainExecutable - Return the path to the main executable, given the
00126 /// value of argv[0] from program startup.
00127 std::string getMainExecutable(const char *argv0, void *MainAddr) {
00128 #if defined(__APPLE__)
00129   // On OS X the executable path is saved to the stack by dyld. Reading it
00130   // from there is much faster than calling dladdr, especially for large
00131   // binaries with symbols.
00132   char exe_path[MAXPATHLEN];
00133   uint32_t size = sizeof(exe_path);
00134   if (_NSGetExecutablePath(exe_path, &size) == 0) {
00135     char link_path[MAXPATHLEN];
00136     if (realpath(exe_path, link_path))
00137       return link_path;
00138   }
00139 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
00140       defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
00141       defined(__FreeBSD_kernel__)
00142   char exe_path[PATH_MAX];
00143 
00144   if (getprogpath(exe_path, argv0) != NULL)
00145     return exe_path;
00146 #elif defined(__linux__) || defined(__CYGWIN__)
00147   char exe_path[MAXPATHLEN];
00148   StringRef aPath("/proc/self/exe");
00149   if (sys::fs::exists(aPath)) {
00150       // /proc is not always mounted under Linux (chroot for example).
00151       ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
00152       if (len >= 0)
00153           return StringRef(exe_path, len);
00154   } else {
00155       // Fall back to the classical detection.
00156       if (getprogpath(exe_path, argv0) != NULL)
00157           return exe_path;
00158   }
00159 #elif defined(HAVE_DLFCN_H)
00160   // Use dladdr to get executable path if available.
00161   Dl_info DLInfo;
00162   int err = dladdr(MainAddr, &DLInfo);
00163   if (err == 0)
00164     return "";
00165 
00166   // If the filename is a symlink, we need to resolve and return the location of
00167   // the actual executable.
00168   char link_path[MAXPATHLEN];
00169   if (realpath(DLInfo.dli_fname, link_path))
00170     return link_path;
00171 #else
00172 #error GetMainExecutable is not implemented on this host yet.
00173 #endif
00174   return "";
00175 }
00176 
00177 TimeValue file_status::getLastModificationTime() const {
00178   TimeValue Ret;
00179   Ret.fromEpochTime(fs_st_mtime);
00180   return Ret;
00181 }
00182 
00183 UniqueID file_status::getUniqueID() const {
00184   return UniqueID(fs_st_dev, fs_st_ino);
00185 }
00186 
00187 std::error_code current_path(SmallVectorImpl<char> &result) {
00188   result.clear();
00189 
00190   const char *pwd = ::getenv("PWD");
00191   llvm::sys::fs::file_status PWDStatus, DotStatus;
00192   if (pwd && llvm::sys::path::is_absolute(pwd) &&
00193       !llvm::sys::fs::status(pwd, PWDStatus) &&
00194       !llvm::sys::fs::status(".", DotStatus) &&
00195       PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
00196     result.append(pwd, pwd + strlen(pwd));
00197     return std::error_code();
00198   }
00199 
00200 #ifdef MAXPATHLEN
00201   result.reserve(MAXPATHLEN);
00202 #else
00203 // For GNU Hurd
00204   result.reserve(1024);
00205 #endif
00206 
00207   while (true) {
00208     if (::getcwd(result.data(), result.capacity()) == nullptr) {
00209       // See if there was a real error.
00210       if (errno != ENOMEM)
00211         return std::error_code(errno, std::generic_category());
00212       // Otherwise there just wasn't enough space.
00213       result.reserve(result.capacity() * 2);
00214     } else
00215       break;
00216   }
00217 
00218   result.set_size(strlen(result.data()));
00219   return std::error_code();
00220 }
00221 
00222 std::error_code create_directory(const Twine &path, bool IgnoreExisting) {
00223   SmallString<128> path_storage;
00224   StringRef p = path.toNullTerminatedStringRef(path_storage);
00225 
00226   if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
00227     if (errno != EEXIST || !IgnoreExisting)
00228       return std::error_code(errno, std::generic_category());
00229   }
00230 
00231   return std::error_code();
00232 }
00233 
00234 // Note that we are using symbolic link because hard links are not supported by
00235 // all filesystems (SMB doesn't).
00236 std::error_code create_link(const Twine &to, const Twine &from) {
00237   // Get arguments.
00238   SmallString<128> from_storage;
00239   SmallString<128> to_storage;
00240   StringRef f = from.toNullTerminatedStringRef(from_storage);
00241   StringRef t = to.toNullTerminatedStringRef(to_storage);
00242 
00243   if (::symlink(t.begin(), f.begin()) == -1)
00244     return std::error_code(errno, std::generic_category());
00245 
00246   return std::error_code();
00247 }
00248 
00249 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
00250   SmallString<128> path_storage;
00251   StringRef p = path.toNullTerminatedStringRef(path_storage);
00252 
00253   struct stat buf;
00254   if (lstat(p.begin(), &buf) != 0) {
00255     if (errno != ENOENT || !IgnoreNonExisting)
00256       return std::error_code(errno, std::generic_category());
00257     return std::error_code();
00258   }
00259 
00260   // Note: this check catches strange situations. In all cases, LLVM should
00261   // only be involved in the creation and deletion of regular files.  This
00262   // check ensures that what we're trying to erase is a regular file. It
00263   // effectively prevents LLVM from erasing things like /dev/null, any block
00264   // special file, or other things that aren't "regular" files.
00265   if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
00266     return make_error_code(errc::operation_not_permitted);
00267 
00268   if (::remove(p.begin()) == -1) {
00269     if (errno != ENOENT || !IgnoreNonExisting)
00270       return std::error_code(errno, std::generic_category());
00271   }
00272 
00273   return std::error_code();
00274 }
00275 
00276 std::error_code rename(const Twine &from, const Twine &to) {
00277   // Get arguments.
00278   SmallString<128> from_storage;
00279   SmallString<128> to_storage;
00280   StringRef f = from.toNullTerminatedStringRef(from_storage);
00281   StringRef t = to.toNullTerminatedStringRef(to_storage);
00282 
00283   if (::rename(f.begin(), t.begin()) == -1)
00284     return std::error_code(errno, std::generic_category());
00285 
00286   return std::error_code();
00287 }
00288 
00289 std::error_code resize_file(int FD, uint64_t Size) {
00290   if (::ftruncate(FD, Size) == -1)
00291     return std::error_code(errno, std::generic_category());
00292 
00293   return std::error_code();
00294 }
00295 
00296 static int convertAccessMode(AccessMode Mode) {
00297   switch (Mode) {
00298   case AccessMode::Exist:
00299     return F_OK;
00300   case AccessMode::Write:
00301     return W_OK;
00302   case AccessMode::Execute:
00303     return R_OK | X_OK; // scripts also need R_OK.
00304   }
00305   llvm_unreachable("invalid enum");
00306 }
00307 
00308 std::error_code access(const Twine &Path, AccessMode Mode) {
00309   SmallString<128> PathStorage;
00310   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
00311 
00312   if (::access(P.begin(), convertAccessMode(Mode)) == -1)
00313     return std::error_code(errno, std::generic_category());
00314 
00315   if (Mode == AccessMode::Execute) {
00316     // Don't say that directories are executable.
00317     struct stat buf;
00318     if (0 != stat(P.begin(), &buf))
00319       return errc::permission_denied;
00320     if (!S_ISREG(buf.st_mode))
00321       return errc::permission_denied;
00322   }
00323 
00324   return std::error_code();
00325 }
00326 
00327 bool equivalent(file_status A, file_status B) {
00328   assert(status_known(A) && status_known(B));
00329   return A.fs_st_dev == B.fs_st_dev &&
00330          A.fs_st_ino == B.fs_st_ino;
00331 }
00332 
00333 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
00334   file_status fsA, fsB;
00335   if (std::error_code ec = status(A, fsA))
00336     return ec;
00337   if (std::error_code ec = status(B, fsB))
00338     return ec;
00339   result = equivalent(fsA, fsB);
00340   return std::error_code();
00341 }
00342 
00343 static std::error_code fillStatus(int StatRet, const struct stat &Status,
00344                              file_status &Result) {
00345   if (StatRet != 0) {
00346     std::error_code ec(errno, std::generic_category());
00347     if (ec == errc::no_such_file_or_directory)
00348       Result = file_status(file_type::file_not_found);
00349     else
00350       Result = file_status(file_type::status_error);
00351     return ec;
00352   }
00353 
00354   file_type Type = file_type::type_unknown;
00355 
00356   if (S_ISDIR(Status.st_mode))
00357     Type = file_type::directory_file;
00358   else if (S_ISREG(Status.st_mode))
00359     Type = file_type::regular_file;
00360   else if (S_ISBLK(Status.st_mode))
00361     Type = file_type::block_file;
00362   else if (S_ISCHR(Status.st_mode))
00363     Type = file_type::character_file;
00364   else if (S_ISFIFO(Status.st_mode))
00365     Type = file_type::fifo_file;
00366   else if (S_ISSOCK(Status.st_mode))
00367     Type = file_type::socket_file;
00368 
00369   perms Perms = static_cast<perms>(Status.st_mode);
00370   Result =
00371       file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
00372                   Status.st_uid, Status.st_gid, Status.st_size);
00373 
00374   return std::error_code();
00375 }
00376 
00377 std::error_code status(const Twine &Path, file_status &Result) {
00378   SmallString<128> PathStorage;
00379   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
00380 
00381   struct stat Status;
00382   int StatRet = ::stat(P.begin(), &Status);
00383   return fillStatus(StatRet, Status, Result);
00384 }
00385 
00386 std::error_code status(int FD, file_status &Result) {
00387   struct stat Status;
00388   int StatRet = ::fstat(FD, &Status);
00389   return fillStatus(StatRet, Status, Result);
00390 }
00391 
00392 std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
00393 #if defined(HAVE_FUTIMENS)
00394   timespec Times[2];
00395   Times[0].tv_sec = Time.toEpochTime();
00396   Times[0].tv_nsec = 0;
00397   Times[1] = Times[0];
00398   if (::futimens(FD, Times))
00399     return std::error_code(errno, std::generic_category());
00400   return std::error_code();
00401 #elif defined(HAVE_FUTIMES)
00402   timeval Times[2];
00403   Times[0].tv_sec = Time.toEpochTime();
00404   Times[0].tv_usec = 0;
00405   Times[1] = Times[0];
00406   if (::futimes(FD, Times))
00407     return std::error_code(errno, std::generic_category());
00408   return std::error_code();
00409 #else
00410 #warning Missing futimes() and futimens()
00411   return make_error_code(errc::function_not_supported);
00412 #endif
00413 }
00414 
00415 std::error_code mapped_file_region::init(int FD, uint64_t Offset,
00416                                          mapmode Mode) {
00417   assert(Size != 0);
00418 
00419   int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
00420   int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
00421   Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
00422   if (Mapping == MAP_FAILED)
00423     return std::error_code(errno, std::generic_category());
00424   return std::error_code();
00425 }
00426 
00427 mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
00428                                        uint64_t offset, std::error_code &ec)
00429     : Size(length), Mapping() {
00430   // Make sure that the requested size fits within SIZE_T.
00431   if (length > std::numeric_limits<size_t>::max()) {
00432     ec = make_error_code(errc::invalid_argument);
00433     return;
00434   }
00435 
00436   ec = init(fd, offset, mode);
00437   if (ec)
00438     Mapping = nullptr;
00439 }
00440 
00441 mapped_file_region::~mapped_file_region() {
00442   if (Mapping)
00443     ::munmap(Mapping, Size);
00444 }
00445 
00446 uint64_t mapped_file_region::size() const {
00447   assert(Mapping && "Mapping failed but used anyway!");
00448   return Size;
00449 }
00450 
00451 char *mapped_file_region::data() const {
00452   assert(Mapping && "Mapping failed but used anyway!");
00453   return reinterpret_cast<char*>(Mapping);
00454 }
00455 
00456 const char *mapped_file_region::const_data() const {
00457   assert(Mapping && "Mapping failed but used anyway!");
00458   return reinterpret_cast<const char*>(Mapping);
00459 }
00460 
00461 int mapped_file_region::alignment() {
00462   return Process::getPageSize();
00463 }
00464 
00465 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
00466                                                 StringRef path){
00467   SmallString<128> path_null(path);
00468   DIR *directory = ::opendir(path_null.c_str());
00469   if (!directory)
00470     return std::error_code(errno, std::generic_category());
00471 
00472   it.IterationHandle = reinterpret_cast<intptr_t>(directory);
00473   // Add something for replace_filename to replace.
00474   path::append(path_null, ".");
00475   it.CurrentEntry = directory_entry(path_null.str());
00476   return directory_iterator_increment(it);
00477 }
00478 
00479 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
00480   if (it.IterationHandle)
00481     ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
00482   it.IterationHandle = 0;
00483   it.CurrentEntry = directory_entry();
00484   return std::error_code();
00485 }
00486 
00487 std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
00488   errno = 0;
00489   dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
00490   if (cur_dir == nullptr && errno != 0) {
00491     return std::error_code(errno, std::generic_category());
00492   } else if (cur_dir != nullptr) {
00493     StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
00494     if ((name.size() == 1 && name[0] == '.') ||
00495         (name.size() == 2 && name[0] == '.' && name[1] == '.'))
00496       return directory_iterator_increment(it);
00497     it.CurrentEntry.replace_filename(name);
00498   } else
00499     return directory_iterator_destruct(it);
00500 
00501   return std::error_code();
00502 }
00503 
00504 std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
00505   SmallString<128> Storage;
00506   StringRef P = Name.toNullTerminatedStringRef(Storage);
00507   while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
00508     if (errno != EINTR)
00509       return std::error_code(errno, std::generic_category());
00510   }
00511   return std::error_code();
00512 }
00513 
00514 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
00515                             sys::fs::OpenFlags Flags, unsigned Mode) {
00516   // Verify that we don't have both "append" and "excl".
00517   assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
00518          "Cannot specify both 'excl' and 'append' file creation flags!");
00519 
00520   int OpenFlags = O_CREAT;
00521 
00522   if (Flags & F_RW)
00523     OpenFlags |= O_RDWR;
00524   else
00525     OpenFlags |= O_WRONLY;
00526 
00527   if (Flags & F_Append)
00528     OpenFlags |= O_APPEND;
00529   else
00530     OpenFlags |= O_TRUNC;
00531 
00532   if (Flags & F_Excl)
00533     OpenFlags |= O_EXCL;
00534 
00535   SmallString<128> Storage;
00536   StringRef P = Name.toNullTerminatedStringRef(Storage);
00537   while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
00538     if (errno != EINTR)
00539       return std::error_code(errno, std::generic_category());
00540   }
00541   return std::error_code();
00542 }
00543 
00544 } // end namespace fs
00545 
00546 namespace path {
00547 
00548 bool home_directory(SmallVectorImpl<char> &result) {
00549   if (char *RequestedDir = getenv("HOME")) {
00550     result.clear();
00551     result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
00552     return true;
00553   }
00554 
00555   return false;
00556 }
00557 
00558 static const char *getEnvTempDir() {
00559   // Check whether the temporary directory is specified by an environment
00560   // variable.
00561   const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
00562   for (const char *Env : EnvironmentVariables) {
00563     if (const char *Dir = std::getenv(Env))
00564       return Dir;
00565   }
00566 
00567   return nullptr;
00568 }
00569 
00570 static const char *getDefaultTempDir(bool ErasedOnReboot) {
00571 #ifdef P_tmpdir
00572   if ((bool)P_tmpdir)
00573     return P_tmpdir;
00574 #endif
00575 
00576   if (ErasedOnReboot)
00577     return "/tmp";
00578   return "/var/tmp";
00579 }
00580 
00581 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
00582   Result.clear();
00583 
00584   if (ErasedOnReboot) {
00585     // There is no env variable for the cache directory.
00586     if (const char *RequestedDir = getEnvTempDir()) {
00587       Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
00588       return;
00589     }
00590   }
00591 
00592 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
00593   // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
00594   // macros defined in <unistd.h> on darwin >= 9
00595   int ConfName = ErasedOnReboot? _CS_DARWIN_USER_TEMP_DIR
00596                                : _CS_DARWIN_USER_CACHE_DIR;
00597   size_t ConfLen = confstr(ConfName, nullptr, 0);
00598   if (ConfLen > 0) {
00599     do {
00600       Result.resize(ConfLen);
00601       ConfLen = confstr(ConfName, Result.data(), Result.size());
00602     } while (ConfLen > 0 && ConfLen != Result.size());
00603 
00604     if (ConfLen > 0) {
00605       assert(Result.back() == 0);
00606       Result.pop_back();
00607       return;
00608     }
00609 
00610     Result.clear();
00611   }
00612 #endif
00613 
00614   const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
00615   Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
00616 }
00617 
00618 } // end namespace path
00619 
00620 } // end namespace sys
00621 } // end namespace llvm