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 {
00066   /// This class automatically closes the given file descriptor when it goes out
00067   /// of scope. You can take back explicit ownership of the file descriptor by
00068   /// calling take(). The destructor does not verify that close was successful.
00069   /// Therefore, never allow this class to call close on a file descriptor that
00070   /// has been read from or written to.
00071   struct AutoFD {
00072     int FileDescriptor;
00073 
00074     AutoFD(int fd) : FileDescriptor(fd) {}
00075     ~AutoFD() {
00076       if (FileDescriptor >= 0)
00077         ::close(FileDescriptor);
00078     }
00079 
00080     int take() {
00081       int ret = FileDescriptor;
00082       FileDescriptor = -1;
00083       return ret;
00084     }
00085 
00086     operator int() const {return FileDescriptor;}
00087   };
00088 }
00089 
00090 static error_code TempDir(SmallVectorImpl<char> &result) {
00091   // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
00092   const char *dir = 0;
00093   (dir = std::getenv("TMPDIR")) || (dir = std::getenv("TMP")) ||
00094       (dir = std::getenv("TEMP")) || (dir = std::getenv("TEMPDIR")) ||
00095 #ifdef P_tmpdir
00096       (dir = P_tmpdir) ||
00097 #endif
00098       (dir = "/tmp");
00099 
00100   result.clear();
00101   StringRef d(dir);
00102   result.append(d.begin(), d.end());
00103   return error_code::success();
00104 }
00105 
00106 namespace llvm {
00107 namespace sys  {
00108 namespace fs {
00109 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
00110     defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
00111     defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
00112 static int
00113 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
00114 {  
00115   struct stat sb;
00116   char fullpath[PATH_MAX];
00117 
00118   snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
00119   if (realpath(fullpath, ret) == NULL)
00120     return (1);
00121   if (stat(fullpath, &sb) != 0)
00122     return (1);
00123 
00124   return (0);
00125 }
00126 
00127 static char *
00128 getprogpath(char ret[PATH_MAX], const char *bin)
00129 {
00130   char *pv, *s, *t;
00131 
00132   /* First approach: absolute path. */
00133   if (bin[0] == '/') {
00134     if (test_dir(ret, "/", bin) == 0)
00135       return (ret);
00136     return (NULL);
00137   }
00138 
00139   /* Second approach: relative path. */
00140   if (strchr(bin, '/') != NULL) {
00141     char cwd[PATH_MAX];
00142     if (getcwd(cwd, PATH_MAX) == NULL)
00143       return (NULL);
00144     if (test_dir(ret, cwd, bin) == 0)
00145       return (ret);
00146     return (NULL);
00147   }
00148 
00149   /* Third approach: $PATH */
00150   if ((pv = getenv("PATH")) == NULL)
00151     return (NULL);
00152   s = pv = strdup(pv);
00153   if (pv == NULL)
00154     return (NULL);
00155   while ((t = strsep(&s, ":")) != NULL) {
00156     if (test_dir(ret, t, bin) == 0) {
00157       free(pv);
00158       return (ret);
00159     }
00160   }
00161   free(pv);
00162   return (NULL);
00163 }
00164 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
00165 
00166 /// GetMainExecutable - Return the path to the main executable, given the
00167 /// value of argv[0] from program startup.
00168 std::string getMainExecutable(const char *argv0, void *MainAddr) {
00169 #if defined(__APPLE__)
00170   // On OS X the executable path is saved to the stack by dyld. Reading it
00171   // from there is much faster than calling dladdr, especially for large
00172   // binaries with symbols.
00173   char exe_path[MAXPATHLEN];
00174   uint32_t size = sizeof(exe_path);
00175   if (_NSGetExecutablePath(exe_path, &size) == 0) {
00176     char link_path[MAXPATHLEN];
00177     if (realpath(exe_path, link_path))
00178       return link_path;
00179   }
00180 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
00181       defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
00182       defined(__FreeBSD_kernel__)
00183   char exe_path[PATH_MAX];
00184 
00185   if (getprogpath(exe_path, argv0) != NULL)
00186     return exe_path;
00187 #elif defined(__linux__) || defined(__CYGWIN__)
00188   char exe_path[MAXPATHLEN];
00189   StringRef aPath("/proc/self/exe");
00190   if (sys::fs::exists(aPath)) {
00191       // /proc is not always mounted under Linux (chroot for example).
00192       ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
00193       if (len >= 0)
00194           return StringRef(exe_path, len);
00195   } else {
00196       // Fall back to the classical detection.
00197       if (getprogpath(exe_path, argv0) != NULL)
00198           return exe_path;
00199   }
00200 #elif defined(HAVE_DLFCN_H)
00201   // Use dladdr to get executable path if available.
00202   Dl_info DLInfo;
00203   int err = dladdr(MainAddr, &DLInfo);
00204   if (err == 0)
00205     return "";
00206 
00207   // If the filename is a symlink, we need to resolve and return the location of
00208   // the actual executable.
00209   char link_path[MAXPATHLEN];
00210   if (realpath(DLInfo.dli_fname, link_path))
00211     return link_path;
00212 #else
00213 #error GetMainExecutable is not implemented on this host yet.
00214 #endif
00215   return "";
00216 }
00217 
00218 TimeValue file_status::getLastModificationTime() const {
00219   TimeValue Ret;
00220   Ret.fromEpochTime(fs_st_mtime);
00221   return Ret;
00222 }
00223 
00224 UniqueID file_status::getUniqueID() const {
00225   return UniqueID(fs_st_dev, fs_st_ino);
00226 }
00227 
00228 error_code current_path(SmallVectorImpl<char> &result) {
00229   result.clear();
00230 
00231   const char *pwd = ::getenv("PWD");
00232   llvm::sys::fs::file_status PWDStatus, DotStatus;
00233   if (pwd && llvm::sys::path::is_absolute(pwd) &&
00234       !llvm::sys::fs::status(pwd, PWDStatus) &&
00235       !llvm::sys::fs::status(".", DotStatus) &&
00236       PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
00237     result.append(pwd, pwd + strlen(pwd));
00238     return error_code::success();
00239   }
00240 
00241 #ifdef MAXPATHLEN
00242   result.reserve(MAXPATHLEN);
00243 #else
00244 // For GNU Hurd
00245   result.reserve(1024);
00246 #endif
00247 
00248   while (true) {
00249     if (::getcwd(result.data(), result.capacity()) == 0) {
00250       // See if there was a real error.
00251       if (errno != errc::not_enough_memory)
00252         return error_code(errno, system_category());
00253       // Otherwise there just wasn't enough space.
00254       result.reserve(result.capacity() * 2);
00255     } else
00256       break;
00257   }
00258 
00259   result.set_size(strlen(result.data()));
00260   return error_code::success();
00261 }
00262 
00263 error_code create_directory(const Twine &path, bool IgnoreExisting) {
00264   SmallString<128> path_storage;
00265   StringRef p = path.toNullTerminatedStringRef(path_storage);
00266 
00267   if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
00268     if (errno != errc::file_exists || !IgnoreExisting)
00269       return error_code(errno, system_category());
00270   }
00271 
00272   return error_code::success();
00273 }
00274 
00275 error_code normalize_separators(SmallVectorImpl<char> &Path) {
00276   for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
00277     if (*PI == '\\') {
00278       auto PN = PI + 1;
00279       if (PN < PE && *PN == '\\')
00280         ++PI; // increment once, the for loop will move over the escaped slash
00281       else
00282         *PI = '/';
00283     }
00284   }
00285   return error_code::success();
00286 }
00287 
00288 // Note that we are using symbolic link because hard links are not supported by
00289 // all filesystems (SMB doesn't).
00290 error_code create_link(const Twine &to, const Twine &from) {
00291   // Get arguments.
00292   SmallString<128> from_storage;
00293   SmallString<128> to_storage;
00294   StringRef f = from.toNullTerminatedStringRef(from_storage);
00295   StringRef t = to.toNullTerminatedStringRef(to_storage);
00296 
00297   if (::symlink(t.begin(), f.begin()) == -1)
00298     return error_code(errno, system_category());
00299 
00300   return error_code::success();
00301 }
00302 
00303 error_code remove(const Twine &path, bool IgnoreNonExisting) {
00304   SmallString<128> path_storage;
00305   StringRef p = path.toNullTerminatedStringRef(path_storage);
00306 
00307   struct stat buf;
00308   if (lstat(p.begin(), &buf) != 0) {
00309     if (errno != errc::no_such_file_or_directory || !IgnoreNonExisting)
00310       return error_code(errno, system_category());
00311     return error_code::success();
00312   }
00313 
00314   // Note: this check catches strange situations. In all cases, LLVM should
00315   // only be involved in the creation and deletion of regular files.  This
00316   // check ensures that what we're trying to erase is a regular file. It
00317   // effectively prevents LLVM from erasing things like /dev/null, any block
00318   // special file, or other things that aren't "regular" files.
00319   if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
00320     return make_error_code(errc::operation_not_permitted);
00321 
00322   if (::remove(p.begin()) == -1) {
00323     if (errno != errc::no_such_file_or_directory || !IgnoreNonExisting)
00324       return error_code(errno, system_category());
00325   }
00326 
00327   return error_code::success();
00328 }
00329 
00330 error_code rename(const Twine &from, const Twine &to) {
00331   // Get arguments.
00332   SmallString<128> from_storage;
00333   SmallString<128> to_storage;
00334   StringRef f = from.toNullTerminatedStringRef(from_storage);
00335   StringRef t = to.toNullTerminatedStringRef(to_storage);
00336 
00337   if (::rename(f.begin(), t.begin()) == -1)
00338     return error_code(errno, system_category());
00339 
00340   return error_code::success();
00341 }
00342 
00343 error_code resize_file(const Twine &path, uint64_t size) {
00344   SmallString<128> path_storage;
00345   StringRef p = path.toNullTerminatedStringRef(path_storage);
00346 
00347   if (::truncate(p.begin(), size) == -1)
00348     return error_code(errno, system_category());
00349 
00350   return error_code::success();
00351 }
00352 
00353 error_code exists(const Twine &path, bool &result) {
00354   SmallString<128> path_storage;
00355   StringRef p = path.toNullTerminatedStringRef(path_storage);
00356 
00357   if (::access(p.begin(), F_OK) == -1) {
00358     if (errno != errc::no_such_file_or_directory)
00359       return error_code(errno, system_category());
00360     result = false;
00361   } else
00362     result = true;
00363 
00364   return error_code::success();
00365 }
00366 
00367 bool can_write(const Twine &Path) {
00368   SmallString<128> PathStorage;
00369   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
00370   return 0 == access(P.begin(), W_OK);
00371 }
00372 
00373 bool can_execute(const Twine &Path) {
00374   SmallString<128> PathStorage;
00375   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
00376 
00377   if (0 != access(P.begin(), R_OK | X_OK))
00378     return false;
00379   struct stat buf;
00380   if (0 != stat(P.begin(), &buf))
00381     return false;
00382   if (!S_ISREG(buf.st_mode))
00383     return false;
00384   return true;
00385 }
00386 
00387 bool equivalent(file_status A, file_status B) {
00388   assert(status_known(A) && status_known(B));
00389   return A.fs_st_dev == B.fs_st_dev &&
00390          A.fs_st_ino == B.fs_st_ino;
00391 }
00392 
00393 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
00394   file_status fsA, fsB;
00395   if (error_code ec = status(A, fsA)) return ec;
00396   if (error_code ec = status(B, fsB)) return ec;
00397   result = equivalent(fsA, fsB);
00398   return error_code::success();
00399 }
00400 
00401 static error_code fillStatus(int StatRet, const struct stat &Status,
00402                              file_status &Result) {
00403   if (StatRet != 0) {
00404     error_code ec(errno, system_category());
00405     if (ec == errc::no_such_file_or_directory)
00406       Result = file_status(file_type::file_not_found);
00407     else
00408       Result = file_status(file_type::status_error);
00409     return ec;
00410   }
00411 
00412   file_type Type = file_type::type_unknown;
00413 
00414   if (S_ISDIR(Status.st_mode))
00415     Type = file_type::directory_file;
00416   else if (S_ISREG(Status.st_mode))
00417     Type = file_type::regular_file;
00418   else if (S_ISBLK(Status.st_mode))
00419     Type = file_type::block_file;
00420   else if (S_ISCHR(Status.st_mode))
00421     Type = file_type::character_file;
00422   else if (S_ISFIFO(Status.st_mode))
00423     Type = file_type::fifo_file;
00424   else if (S_ISSOCK(Status.st_mode))
00425     Type = file_type::socket_file;
00426 
00427   perms Perms = static_cast<perms>(Status.st_mode);
00428   Result =
00429       file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
00430                   Status.st_uid, Status.st_gid, Status.st_size);
00431 
00432   return error_code::success();
00433 }
00434 
00435 error_code status(const Twine &Path, file_status &Result) {
00436   SmallString<128> PathStorage;
00437   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
00438 
00439   struct stat Status;
00440   int StatRet = ::stat(P.begin(), &Status);
00441   return fillStatus(StatRet, Status, Result);
00442 }
00443 
00444 error_code status(int FD, file_status &Result) {
00445   struct stat Status;
00446   int StatRet = ::fstat(FD, &Status);
00447   return fillStatus(StatRet, Status, Result);
00448 }
00449 
00450 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
00451 #if defined(HAVE_FUTIMENS)
00452   timespec Times[2];
00453   Times[0].tv_sec = Time.toEpochTime();
00454   Times[0].tv_nsec = 0;
00455   Times[1] = Times[0];
00456   if (::futimens(FD, Times))
00457     return error_code(errno, system_category());
00458   return error_code::success();
00459 #elif defined(HAVE_FUTIMES)
00460   timeval Times[2];
00461   Times[0].tv_sec = Time.toEpochTime();
00462   Times[0].tv_usec = 0;
00463   Times[1] = Times[0];
00464   if (::futimes(FD, Times))
00465     return error_code(errno, system_category());
00466   return error_code::success();
00467 #else
00468 #warning Missing futimes() and futimens()
00469   return make_error_code(errc::not_supported);
00470 #endif
00471 }
00472 
00473 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
00474   AutoFD ScopedFD(FD);
00475   if (!CloseFD)
00476     ScopedFD.take();
00477 
00478   // Figure out how large the file is.
00479   struct stat FileInfo;
00480   if (fstat(FD, &FileInfo) == -1)
00481     return error_code(errno, system_category());
00482   uint64_t FileSize = FileInfo.st_size;
00483 
00484   if (Size == 0)
00485     Size = FileSize;
00486   else if (FileSize < Size) {
00487     // We need to grow the file.
00488     if (ftruncate(FD, Size) == -1)
00489       return error_code(errno, system_category());
00490   }
00491 
00492   int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
00493   int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
00494 #ifdef MAP_FILE
00495   flags |= MAP_FILE;
00496 #endif
00497   Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
00498   if (Mapping == MAP_FAILED)
00499     return error_code(errno, system_category());
00500   return error_code::success();
00501 }
00502 
00503 mapped_file_region::mapped_file_region(const Twine &path,
00504                                        mapmode mode,
00505                                        uint64_t length,
00506                                        uint64_t offset,
00507                                        error_code &ec)
00508   : Mode(mode)
00509   , Size(length)
00510   , Mapping() {
00511   // Make sure that the requested size fits within SIZE_T.
00512   if (length > std::numeric_limits<size_t>::max()) {
00513     ec = make_error_code(errc::invalid_argument);
00514     return;
00515   }
00516 
00517   SmallString<128> path_storage;
00518   StringRef name = path.toNullTerminatedStringRef(path_storage);
00519   int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
00520   int ofd = ::open(name.begin(), oflags);
00521   if (ofd == -1) {
00522     ec = error_code(errno, system_category());
00523     return;
00524   }
00525 
00526   ec = init(ofd, true, offset);
00527   if (ec)
00528     Mapping = 0;
00529 }
00530 
00531 mapped_file_region::mapped_file_region(int fd,
00532                                        bool closefd,
00533                                        mapmode mode,
00534                                        uint64_t length,
00535                                        uint64_t offset,
00536                                        error_code &ec)
00537   : Mode(mode)
00538   , Size(length)
00539   , Mapping() {
00540   // Make sure that the requested size fits within SIZE_T.
00541   if (length > std::numeric_limits<size_t>::max()) {
00542     ec = make_error_code(errc::invalid_argument);
00543     return;
00544   }
00545 
00546   ec = init(fd, closefd, offset);
00547   if (ec)
00548     Mapping = 0;
00549 }
00550 
00551 mapped_file_region::~mapped_file_region() {
00552   if (Mapping)
00553     ::munmap(Mapping, Size);
00554 }
00555 
00556 mapped_file_region::mapped_file_region(mapped_file_region &&other)
00557   : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
00558   other.Mapping = 0;
00559 }
00560 
00561 mapped_file_region::mapmode mapped_file_region::flags() const {
00562   assert(Mapping && "Mapping failed but used anyway!");
00563   return Mode;
00564 }
00565 
00566 uint64_t mapped_file_region::size() const {
00567   assert(Mapping && "Mapping failed but used anyway!");
00568   return Size;
00569 }
00570 
00571 char *mapped_file_region::data() const {
00572   assert(Mapping && "Mapping failed but used anyway!");
00573   assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
00574   return reinterpret_cast<char*>(Mapping);
00575 }
00576 
00577 const char *mapped_file_region::const_data() const {
00578   assert(Mapping && "Mapping failed but used anyway!");
00579   return reinterpret_cast<const char*>(Mapping);
00580 }
00581 
00582 int mapped_file_region::alignment() {
00583   return process::get_self()->page_size();
00584 }
00585 
00586 error_code detail::directory_iterator_construct(detail::DirIterState &it,
00587                                                 StringRef path){
00588   SmallString<128> path_null(path);
00589   DIR *directory = ::opendir(path_null.c_str());
00590   if (directory == 0)
00591     return error_code(errno, system_category());
00592 
00593   it.IterationHandle = reinterpret_cast<intptr_t>(directory);
00594   // Add something for replace_filename to replace.
00595   path::append(path_null, ".");
00596   it.CurrentEntry = directory_entry(path_null.str());
00597   return directory_iterator_increment(it);
00598 }
00599 
00600 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
00601   if (it.IterationHandle)
00602     ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
00603   it.IterationHandle = 0;
00604   it.CurrentEntry = directory_entry();
00605   return error_code::success();
00606 }
00607 
00608 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
00609   errno = 0;
00610   dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
00611   if (cur_dir == 0 && errno != 0) {
00612     return error_code(errno, system_category());
00613   } else if (cur_dir != 0) {
00614     StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
00615     if ((name.size() == 1 && name[0] == '.') ||
00616         (name.size() == 2 && name[0] == '.' && name[1] == '.'))
00617       return directory_iterator_increment(it);
00618     it.CurrentEntry.replace_filename(name);
00619   } else
00620     return directory_iterator_destruct(it);
00621 
00622   return error_code::success();
00623 }
00624 
00625 error_code get_magic(const Twine &path, uint32_t len,
00626                      SmallVectorImpl<char> &result) {
00627   SmallString<128> PathStorage;
00628   StringRef Path = path.toNullTerminatedStringRef(PathStorage);
00629   result.set_size(0);
00630 
00631   // Open path.
00632   std::FILE *file = std::fopen(Path.data(), "rb");
00633   if (file == 0)
00634     return error_code(errno, system_category());
00635 
00636   // Reserve storage.
00637   result.reserve(len);
00638 
00639   // Read magic!
00640   size_t size = std::fread(result.data(), 1, len, file);
00641   if (std::ferror(file) != 0) {
00642     std::fclose(file);
00643     return error_code(errno, system_category());
00644   } else if (size != len) {
00645     if (std::feof(file) != 0) {
00646       std::fclose(file);
00647       result.set_size(size);
00648       return make_error_code(errc::value_too_large);
00649     }
00650   }
00651   std::fclose(file);
00652   result.set_size(size);
00653   return error_code::success();
00654 }
00655 
00656 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,  
00657                                             bool map_writable, void *&result) {
00658   SmallString<128> path_storage;
00659   StringRef name = path.toNullTerminatedStringRef(path_storage);
00660   int oflags = map_writable ? O_RDWR : O_RDONLY;
00661   int ofd = ::open(name.begin(), oflags);
00662   if ( ofd == -1 )
00663     return error_code(errno, system_category());
00664   AutoFD fd(ofd);
00665   int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
00666   int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
00667 #ifdef MAP_FILE
00668   flags |= MAP_FILE;
00669 #endif
00670   result = ::mmap(0, size, prot, flags, fd, file_offset);
00671   if (result == MAP_FAILED) {
00672     return error_code(errno, system_category());
00673   }
00674   
00675   return error_code::success();
00676 }
00677 
00678 error_code unmap_file_pages(void *base, size_t size) {
00679   if ( ::munmap(base, size) == -1 )
00680     return error_code(errno, system_category());
00681    
00682   return error_code::success();
00683 }
00684 
00685 error_code openFileForRead(const Twine &Name, int &ResultFD) {
00686   SmallString<128> Storage;
00687   StringRef P = Name.toNullTerminatedStringRef(Storage);
00688   while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
00689     if (errno != EINTR)
00690       return error_code(errno, system_category());
00691   }
00692   return error_code::success();
00693 }
00694 
00695 error_code openFileForWrite(const Twine &Name, int &ResultFD,
00696                             sys::fs::OpenFlags Flags, unsigned Mode) {
00697   // Verify that we don't have both "append" and "excl".
00698   assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
00699          "Cannot specify both 'excl' and 'append' file creation flags!");
00700 
00701   int OpenFlags = O_CREAT;
00702 
00703   if (Flags & F_RW)
00704     OpenFlags |= O_RDWR;
00705   else
00706     OpenFlags |= O_WRONLY;
00707 
00708   if (Flags & F_Append)
00709     OpenFlags |= O_APPEND;
00710   else
00711     OpenFlags |= O_TRUNC;
00712 
00713   if (Flags & F_Excl)
00714     OpenFlags |= O_EXCL;
00715 
00716   SmallString<128> Storage;
00717   StringRef P = Name.toNullTerminatedStringRef(Storage);
00718   while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
00719     if (errno != EINTR)
00720       return error_code(errno, system_category());
00721   }
00722   return error_code::success();
00723 }
00724 
00725 } // end namespace fs
00726 
00727 namespace path {
00728 
00729 bool home_directory(SmallVectorImpl<char> &result) {
00730   if (char *RequestedDir = getenv("HOME")) {
00731     result.clear();
00732     result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
00733     return true;
00734   }
00735 
00736   return false;
00737 }
00738 
00739 } // end namespace path
00740 
00741 } // end namespace sys
00742 } // end namespace llvm