LLVM API Documentation

Unix/Path.inc

Go to the documentation of this file.
00001 //===- llvm/System/Unix/Path.cpp - 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 portion of the Path class.
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 "llvm/Config/alloca.h"
00020 #include "Unix.h"
00021 #if HAVE_SYS_STAT_H
00022 #include <sys/stat.h>
00023 #endif
00024 #if HAVE_FCNTL_H
00025 #include <fcntl.h>
00026 #endif
00027 #ifdef HAVE_SYS_MMAN_H
00028 #include <sys/mman.h>
00029 #endif
00030 #ifdef HAVE_SYS_STAT_H
00031 #include <sys/stat.h>
00032 #endif
00033 #if HAVE_UTIME_H
00034 #include <utime.h>
00035 #endif
00036 #if HAVE_TIME_H
00037 #include <time.h>
00038 #endif
00039 #if HAVE_DIRENT_H
00040 # include <dirent.h>
00041 # define NAMLEN(dirent) strlen((dirent)->d_name)
00042 #else
00043 # define dirent direct
00044 # define NAMLEN(dirent) (dirent)->d_namlen
00045 # if HAVE_SYS_NDIR_H
00046 #  include <sys/ndir.h>
00047 # endif
00048 # if HAVE_SYS_DIR_H
00049 #  include <sys/dir.h>
00050 # endif
00051 # if HAVE_NDIR_H
00052 #  include <ndir.h>
00053 # endif
00054 #endif
00055 
00056 #if HAVE_DLFCN_H
00057 #include <dlfcn.h>
00058 #endif
00059 
00060 // Put in a hack for Cygwin which falsely reports that the mkdtemp function
00061 // is available when it is not.
00062 #ifdef __CYGWIN__
00063 # undef HAVE_MKDTEMP
00064 #endif
00065 
00066 namespace {
00067 inline bool lastIsSlash(const std::string& path) {
00068   return !path.empty() && path[path.length() - 1] == '/';
00069 }
00070 
00071 }
00072 
00073 namespace llvm {
00074 using namespace sys;
00075 
00076 extern const char sys::PathSeparator = ':';
00077 
00078 Path::Path(const std::string& p)
00079   : path(p) {}
00080 
00081 Path::Path(const char *StrStart, unsigned StrLen)
00082   : path(StrStart, StrLen) {}
00083 
00084 Path&
00085 Path::operator=(const std::string &that) {
00086   path = that;
00087   return *this;
00088 }
00089 
00090 bool
00091 Path::isValid() const {
00092   // Check some obvious things
00093   if (path.empty())
00094     return false;
00095   return path.length() < MAXPATHLEN;
00096 }
00097 
00098 bool
00099 Path::isAbsolute(const char *NameStart, unsigned NameLen) {
00100   assert(NameStart);
00101   if (NameLen == 0)
00102     return false;
00103   return NameStart[0] == '/';
00104 }
00105 
00106 bool
00107 Path::isAbsolute() const {
00108   if (path.empty())
00109     return false;
00110   return path[0] == '/';
00111 }
00112 
00113 void Path::makeAbsolute() {
00114   if (isAbsolute())
00115     return;
00116 
00117   Path CWD = Path::GetCurrentDirectory();
00118   assert(CWD.isAbsolute() && "GetCurrentDirectory returned relative path!");
00119 
00120   CWD.appendComponent(path);
00121 
00122   path = CWD.toString();
00123 }
00124 
00125 Path
00126 Path::GetRootDirectory() {
00127   Path result;
00128   result.set("/");
00129   return result;
00130 }
00131 
00132 Path
00133 Path::GetTemporaryDirectory(std::string *ErrMsg) {
00134 #if defined(HAVE_MKDTEMP)
00135   // The best way is with mkdtemp but that's not available on many systems,
00136   // Linux and FreeBSD have it. Others probably won't.
00137   char pathname[MAXPATHLEN];
00138   strcpy(pathname,"/tmp/llvm_XXXXXX");
00139   if (0 == mkdtemp(pathname)) {
00140     MakeErrMsg(ErrMsg,
00141       std::string(pathname) + ": can't create temporary directory");
00142     return Path();
00143   }
00144   Path result;
00145   result.set(pathname);
00146   assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
00147   return result;
00148 #elif defined(HAVE_MKSTEMP)
00149   // If no mkdtemp is available, mkstemp can be used to create a temporary file
00150   // which is then removed and created as a directory. We prefer this over
00151   // mktemp because of mktemp's inherent security and threading risks. We still
00152   // have a slight race condition from the time the temporary file is created to
00153   // the time it is re-created as a directoy.
00154   char pathname[MAXPATHLEN];
00155   strcpy(pathname, "/tmp/llvm_XXXXXX");
00156   int fd = 0;
00157   if (-1 == (fd = mkstemp(pathname))) {
00158     MakeErrMsg(ErrMsg,
00159       std::string(pathname) + ": can't create temporary directory");
00160     return Path();
00161   }
00162   ::close(fd);
00163   ::unlink(pathname); // start race condition, ignore errors
00164   if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
00165     MakeErrMsg(ErrMsg,
00166       std::string(pathname) + ": can't create temporary directory");
00167     return Path();
00168   }
00169   Path result;
00170   result.set(pathname);
00171   assert(result.isValid() && "mkstemp didn't create a valid pathname!");
00172   return result;
00173 #elif defined(HAVE_MKTEMP)
00174   // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
00175   // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
00176   // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
00177   // the XXXXXX with the pid of the process and a letter. That leads to only
00178   // twenty six temporary files that can be generated.
00179   char pathname[MAXPATHLEN];
00180   strcpy(pathname, "/tmp/llvm_XXXXXX");
00181   char *TmpName = ::mktemp(pathname);
00182   if (TmpName == 0) {
00183     MakeErrMsg(ErrMsg,
00184       std::string(TmpName) + ": can't create unique directory name");
00185     return Path();
00186   }
00187   if (-1 == ::mkdir(TmpName, S_IRWXU)) {
00188     MakeErrMsg(ErrMsg,
00189         std::string(TmpName) + ": can't create temporary directory");
00190     return Path();
00191   }
00192   Path result;
00193   result.set(TmpName);
00194   assert(result.isValid() && "mktemp didn't create a valid pathname!");
00195   return result;
00196 #else
00197   // This is the worst case implementation. tempnam(3) leaks memory unless its
00198   // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
00199   // issues. The mktemp(3) function doesn't have enough variability in the
00200   // temporary name generated. So, we provide our own implementation that
00201   // increments an integer from a random number seeded by the current time. This
00202   // should be sufficiently unique that we don't have many collisions between
00203   // processes. Generally LLVM processes don't run very long and don't use very
00204   // many temporary files so this shouldn't be a big issue for LLVM.
00205   static time_t num = ::time(0);
00206   char pathname[MAXPATHLEN];
00207   do {
00208     num++;
00209     sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
00210   } while ( 0 == access(pathname, F_OK ) );
00211   if (-1 == ::mkdir(pathname, S_IRWXU)) {
00212     MakeErrMsg(ErrMsg,
00213       std::string(pathname) + ": can't create temporary directory");
00214     return Path();
00215   }
00216   Path result;
00217   result.set(pathname);
00218   assert(result.isValid() && "mkstemp didn't create a valid pathname!");
00219   return result;
00220 #endif
00221 }
00222 
00223 void
00224 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
00225 #ifdef LTDL_SHLIBPATH_VAR
00226   char* env_var = getenv(LTDL_SHLIBPATH_VAR);
00227   if (env_var != 0) {
00228     getPathList(env_var,Paths);
00229   }
00230 #endif
00231   // FIXME: Should this look at LD_LIBRARY_PATH too?
00232   Paths.push_back(sys::Path("/usr/local/lib/"));
00233   Paths.push_back(sys::Path("/usr/X11R6/lib/"));
00234   Paths.push_back(sys::Path("/usr/lib/"));
00235   Paths.push_back(sys::Path("/lib/"));
00236 }
00237 
00238 void
00239 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
00240   char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
00241   if (env_var != 0) {
00242     getPathList(env_var,Paths);
00243   }
00244 #ifdef LLVM_LIBDIR
00245   {
00246     Path tmpPath;
00247     if (tmpPath.set(LLVM_LIBDIR))
00248       if (tmpPath.canRead())
00249         Paths.push_back(tmpPath);
00250   }
00251 #endif
00252   GetSystemLibraryPaths(Paths);
00253 }
00254 
00255 Path
00256 Path::GetLLVMDefaultConfigDir() {
00257   return Path("/etc/llvm/");
00258 }
00259 
00260 Path
00261 Path::GetUserHomeDirectory() {
00262   const char* home = getenv("HOME");
00263   if (home) {
00264     Path result;
00265     if (result.set(home))
00266       return result;
00267   }
00268   return GetRootDirectory();
00269 }
00270 
00271 Path
00272 Path::GetCurrentDirectory() {
00273   char pathname[MAXPATHLEN];
00274   if (!getcwd(pathname,MAXPATHLEN)) {
00275     assert (false && "Could not query current working directory.");
00276     return Path("");
00277   }
00278 
00279   return Path(pathname);
00280 }
00281 
00282 #ifdef __FreeBSD__
00283 static int
00284 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
00285     const char *dir, const char *bin)
00286 {
00287   struct stat sb;
00288 
00289   snprintf(buf, PATH_MAX, "%s//%s", dir, bin);
00290   if (realpath(buf, ret) == NULL)
00291     return (1);
00292   if (stat(buf, &sb) != 0)
00293     return (1);
00294 
00295   return (0);
00296 }
00297 
00298 static char *
00299 getprogpath(char ret[PATH_MAX], const char *bin)
00300 {
00301   char *pv, *s, *t, buf[PATH_MAX];
00302 
00303   /* First approach: absolute path. */
00304   if (bin[0] == '/') {
00305     if (test_dir(buf, ret, "/", bin) == 0)
00306       return (ret);
00307     return (NULL);
00308   }
00309 
00310   /* Second approach: relative path. */
00311   if (strchr(bin, '/') != NULL) {
00312     if (getcwd(buf, PATH_MAX) == NULL)
00313       return (NULL);
00314     if (test_dir(buf, ret, buf, bin) == 0)
00315       return (ret);
00316     return (NULL);
00317   }
00318 
00319   /* Third approach: $PATH */
00320   if ((pv = getenv("PATH")) == NULL)
00321     return (NULL);
00322   s = pv = strdup(pv);
00323   if (pv == NULL)
00324     return (NULL);
00325   while ((t = strsep(&s, ":")) != NULL) {
00326     if (test_dir(buf, ret, t, bin) == 0) {
00327       free(pv);
00328       return (ret);
00329     }
00330   }
00331   free(pv);
00332   return (NULL);
00333 }
00334 #endif
00335 
00336 /// GetMainExecutable - Return the path to the main executable, given the
00337 /// value of argv[0] from program startup.
00338 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
00339 #if defined(__FreeBSD__)
00340   char exe_path[PATH_MAX];
00341 
00342   if (getprogpath(exe_path, argv0) != NULL)
00343     return Path(std::string(exe_path));
00344 #elif defined(__linux__) || defined(__CYGWIN__)
00345   char exe_path[MAXPATHLEN];
00346   ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
00347   if (len >= 0)
00348     return Path(std::string(exe_path, len));
00349 #elif defined(HAVE_DLFCN_H)
00350   // Use dladdr to get executable path if available.
00351   Dl_info DLInfo;
00352   int err = dladdr(MainAddr, &DLInfo);
00353   if (err == 0)
00354     return Path();
00355 
00356   // If the filename is a symlink, we need to resolve and return the location of
00357   // the actual executable.
00358   char link_path[MAXPATHLEN];
00359   return Path(std::string(realpath(DLInfo.dli_fname, link_path)));
00360 #endif
00361   return Path();
00362 }
00363 
00364 
00365 std::string Path::getDirname() const {
00366   return getDirnameCharSep(path, '/');
00367 }
00368 
00369 std::string
00370 Path::getBasename() const {
00371   // Find the last slash
00372   std::string::size_type slash = path.rfind('/');
00373   if (slash == std::string::npos)
00374     slash = 0;
00375   else
00376     slash++;
00377 
00378   std::string::size_type dot = path.rfind('.');
00379   if (dot == std::string::npos || dot < slash)
00380     return path.substr(slash);
00381   else
00382     return path.substr(slash, dot - slash);
00383 }
00384 
00385 std::string
00386 Path::getSuffix() const {
00387   // Find the last slash
00388   std::string::size_type slash = path.rfind('/');
00389   if (slash == std::string::npos)
00390     slash = 0;
00391   else
00392     slash++;
00393 
00394   std::string::size_type dot = path.rfind('.');
00395   if (dot == std::string::npos || dot < slash)
00396     return std::string();
00397   else
00398     return path.substr(dot + 1);
00399 }
00400 
00401 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
00402   assert(len < 1024 && "Request for magic string too long");
00403   char* buf = (char*) alloca(1 + len);
00404   int fd = ::open(path.c_str(), O_RDONLY);
00405   if (fd < 0)
00406     return false;
00407   ssize_t bytes_read = ::read(fd, buf, len);
00408   ::close(fd);
00409   if (ssize_t(len) != bytes_read) {
00410     Magic.clear();
00411     return false;
00412   }
00413   Magic.assign(buf,len);
00414   return true;
00415 }
00416 
00417 bool
00418 Path::exists() const {
00419   return 0 == access(path.c_str(), F_OK );
00420 }
00421 
00422 bool
00423 Path::isDirectory() const {
00424   struct stat buf;
00425   if (0 != stat(path.c_str(), &buf))
00426     return false;
00427   return buf.st_mode & S_IFDIR ? true : false;
00428 }
00429 
00430 bool
00431 Path::canRead() const {
00432   return 0 == access(path.c_str(), R_OK);
00433 }
00434 
00435 bool
00436 Path::canWrite() const {
00437   return 0 == access(path.c_str(), W_OK);
00438 }
00439 
00440 bool
00441 Path::canExecute() const {
00442   if (0 != access(path.c_str(), R_OK | X_OK ))
00443     return false;
00444   struct stat buf;
00445   if (0 != stat(path.c_str(), &buf))
00446     return false;
00447   if (!S_ISREG(buf.st_mode))
00448     return false;
00449   return true;
00450 }
00451 
00452 std::string
00453 Path::getLast() const {
00454   // Find the last slash
00455   size_t pos = path.rfind('/');
00456 
00457   // Handle the corner cases
00458   if (pos == std::string::npos)
00459     return path;
00460 
00461   // If the last character is a slash
00462   if (pos == path.length()-1) {
00463     // Find the second to last slash
00464     size_t pos2 = path.rfind('/', pos-1);
00465     if (pos2 == std::string::npos)
00466       return path.substr(0,pos);
00467     else
00468       return path.substr(pos2+1,pos-pos2-1);
00469   }
00470   // Return everything after the last slash
00471   return path.substr(pos+1);
00472 }
00473 
00474 const FileStatus *
00475 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
00476   if (!fsIsValid || update) {
00477     struct stat buf;
00478     if (0 != stat(path.c_str(), &buf)) {
00479       MakeErrMsg(ErrStr, path + ": can't get status of file");
00480       return 0;
00481     }
00482     status.fileSize = buf.st_size;
00483     status.modTime.fromEpochTime(buf.st_mtime);
00484     status.mode = buf.st_mode;
00485     status.user = buf.st_uid;
00486     status.group = buf.st_gid;
00487     status.uniqueID = uint64_t(buf.st_ino);
00488     status.isDir  = S_ISDIR(buf.st_mode);
00489     status.isFile = S_ISREG(buf.st_mode);
00490     fsIsValid = true;
00491   }
00492   return &status;
00493 }
00494 
00495 static bool AddPermissionBits(const Path &File, int bits) {
00496   // Get the umask value from the operating system.  We want to use it
00497   // when changing the file's permissions. Since calling umask() sets
00498   // the umask and returns its old value, we must call it a second
00499   // time to reset it to the user's preference.
00500   int mask = umask(0777); // The arg. to umask is arbitrary.
00501   umask(mask);            // Restore the umask.
00502 
00503   // Get the file's current mode.
00504   struct stat buf;
00505   if (0 != stat(File.toString().c_str(), &buf))
00506     return false;
00507   // Change the file to have whichever permissions bits from 'bits'
00508   // that the umask would not disable.
00509   if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
00510       return false;
00511   return true;
00512 }
00513 
00514 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
00515   if (!AddPermissionBits(*this, 0444))
00516     return MakeErrMsg(ErrMsg, path + ": can't make file readable");
00517   return false;
00518 }
00519 
00520 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
00521   if (!AddPermissionBits(*this, 0222))
00522     return MakeErrMsg(ErrMsg, path + ": can't make file writable");
00523   return false;
00524 }
00525 
00526 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
00527   if (!AddPermissionBits(*this, 0111))
00528     return MakeErrMsg(ErrMsg, path + ": can't make file executable");
00529   return false;
00530 }
00531 
00532 bool
00533 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
00534   DIR* direntries = ::opendir(path.c_str());
00535   if (direntries == 0)
00536     return MakeErrMsg(ErrMsg, path + ": can't open directory");
00537 
00538   std::string dirPath = path;
00539   if (!lastIsSlash(dirPath))
00540     dirPath += '/';
00541 
00542   result.clear();
00543   struct dirent* de = ::readdir(direntries);
00544   for ( ; de != 0; de = ::readdir(direntries)) {
00545     if (de->d_name[0] != '.') {
00546       Path aPath(dirPath + (const char*)de->d_name);
00547       struct stat st;
00548       if (0 != lstat(aPath.path.c_str(), &st)) {
00549         if (S_ISLNK(st.st_mode))
00550           continue; // dangling symlink -- ignore
00551         return MakeErrMsg(ErrMsg,
00552                           aPath.path +  ": can't determine file object type");
00553       }
00554       result.insert(aPath);
00555     }
00556   }
00557 
00558   closedir(direntries);
00559   return false;
00560 }
00561 
00562 bool
00563 Path::set(const std::string& a_path) {
00564   if (a_path.empty())
00565     return false;
00566   std::string save(path);
00567   path = a_path;
00568   if (!isValid()) {
00569     path = save;
00570     return false;
00571   }
00572   return true;
00573 }
00574 
00575 bool
00576 Path::appendComponent(const std::string& name) {
00577   if (name.empty())
00578     return false;
00579   std::string save(path);
00580   if (!lastIsSlash(path))
00581     path += '/';
00582   path += name;
00583   if (!isValid()) {
00584     path = save;
00585     return false;
00586   }
00587   return true;
00588 }
00589 
00590 bool
00591 Path::eraseComponent() {
00592   size_t slashpos = path.rfind('/',path.size());
00593   if (slashpos == 0 || slashpos == std::string::npos) {
00594     path.erase();
00595     return true;
00596   }
00597   if (slashpos == path.size() - 1)
00598     slashpos = path.rfind('/',slashpos-1);
00599   if (slashpos == std::string::npos) {
00600     path.erase();
00601     return true;
00602   }
00603   path.erase(slashpos);
00604   return true;
00605 }
00606 
00607 bool
00608 Path::appendSuffix(const std::string& suffix) {
00609   std::string save(path);
00610   path.append(".");
00611   path.append(suffix);
00612   if (!isValid()) {
00613     path = save;
00614     return false;
00615   }
00616   return true;
00617 }
00618 
00619 bool
00620 Path::eraseSuffix() {
00621   std::string save = path;
00622   size_t dotpos = path.rfind('.',path.size());
00623   size_t slashpos = path.rfind('/',path.size());
00624   if (dotpos != std::string::npos) {
00625     if (slashpos == std::string::npos || dotpos > slashpos+1) {
00626       path.erase(dotpos, path.size()-dotpos);
00627       return true;
00628     }
00629   }
00630   if (!isValid())
00631     path = save;
00632   return false;
00633 }
00634 
00635 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
00636 
00637   if (access(beg, R_OK | W_OK) == 0)
00638     return false;
00639 
00640   if (create_parents) {
00641 
00642     char* c = end;
00643 
00644     for (; c != beg; --c)
00645       if (*c == '/') {
00646 
00647         // Recurse to handling the parent directory.
00648         *c = '\0';
00649         bool x = createDirectoryHelper(beg, c, create_parents);
00650         *c = '/';
00651 
00652         // Return if we encountered an error.
00653         if (x)
00654           return true;
00655 
00656         break;
00657       }
00658   }
00659 
00660   return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
00661 }
00662 
00663 bool
00664 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
00665   // Get a writeable copy of the path name
00666   char pathname[MAXPATHLEN];
00667   path.copy(pathname,MAXPATHLEN);
00668 
00669   // Null-terminate the last component
00670   size_t lastchar = path.length() - 1 ;
00671 
00672   if (pathname[lastchar] != '/')
00673     ++lastchar;
00674 
00675   pathname[lastchar] = 0;
00676 
00677   if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
00678     return MakeErrMsg(ErrMsg,
00679                       std::string(pathname) + ": can't create directory");
00680 
00681   return false;
00682 }
00683 
00684 bool
00685 Path::createFileOnDisk(std::string* ErrMsg) {
00686   // Create the file
00687   int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
00688   if (fd < 0)
00689     return MakeErrMsg(ErrMsg, path + ": can't create file");
00690   ::close(fd);
00691   return false;
00692 }
00693 
00694 bool
00695 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
00696   // Make this into a unique file name
00697   if (makeUnique( reuse_current, ErrMsg ))
00698     return true;
00699 
00700   // create the file
00701   int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
00702   if (fd < 0)
00703     return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
00704   ::close(fd);
00705   return false;
00706 }
00707 
00708 bool
00709 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
00710   // Get the status so we can determin if its a file or directory
00711   struct stat buf;
00712   if (0 != stat(path.c_str(), &buf)) {
00713     MakeErrMsg(ErrStr, path + ": can't get status of file");
00714     return true;
00715   }
00716 
00717   // Note: this check catches strange situations. In all cases, LLVM should
00718   // only be involved in the creation and deletion of regular files.  This
00719   // check ensures that what we're trying to erase is a regular file. It
00720   // effectively prevents LLVM from erasing things like /dev/null, any block
00721   // special file, or other things that aren't "regular" files.
00722   if (S_ISREG(buf.st_mode)) {
00723     if (unlink(path.c_str()) != 0)
00724       return MakeErrMsg(ErrStr, path + ": can't destroy file");
00725     return false;
00726   }
00727 
00728   if (!S_ISDIR(buf.st_mode)) {
00729     if (ErrStr) *ErrStr = "not a file or directory";
00730     return true;
00731   }
00732 
00733   if (remove_contents) {
00734     // Recursively descend the directory to remove its contents.
00735     std::string cmd = "/bin/rm -rf " + path;
00736     if (system(cmd.c_str()) != 0) {
00737       MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
00738       return true;
00739     }
00740     return false;
00741   }
00742 
00743   // Otherwise, try to just remove the one directory.
00744   char pathname[MAXPATHLEN];
00745   path.copy(pathname, MAXPATHLEN);
00746   size_t lastchar = path.length() - 1;
00747   if (pathname[lastchar] == '/')
00748     pathname[lastchar] = 0;
00749   else
00750     pathname[lastchar+1] = 0;
00751 
00752   if (rmdir(pathname) != 0)
00753     return MakeErrMsg(ErrStr,
00754       std::string(pathname) + ": can't erase directory");
00755   return false;
00756 }
00757 
00758 bool
00759 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
00760   if (0 != ::rename(path.c_str(), newName.c_str()))
00761     return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
00762                newName.toString() + "'");
00763   return false;
00764 }
00765 
00766 bool
00767 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
00768   struct utimbuf utb;
00769   utb.actime = si.modTime.toPosixTime();
00770   utb.modtime = utb.actime;
00771   if (0 != ::utime(path.c_str(),&utb))
00772     return MakeErrMsg(ErrStr, path + ": can't set file modification time");
00773   if (0 != ::chmod(path.c_str(),si.mode))
00774     return MakeErrMsg(ErrStr, path + ": can't set mode");
00775   return false;
00776 }
00777 
00778 bool
00779 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
00780   int inFile = -1;
00781   int outFile = -1;
00782   inFile = ::open(Src.c_str(), O_RDONLY);
00783   if (inFile == -1)
00784     return MakeErrMsg(ErrMsg, Src.toString() +
00785       ": can't open source file to copy");
00786 
00787   outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
00788   if (outFile == -1) {
00789     ::close(inFile);
00790     return MakeErrMsg(ErrMsg, Dest.toString() +
00791       ": can't create destination file for copy");
00792   }
00793 
00794   char Buffer[16*1024];
00795   while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
00796     if (Amt == -1) {
00797       if (errno != EINTR && errno != EAGAIN) {
00798         ::close(inFile);
00799         ::close(outFile);
00800         return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file");
00801       }
00802     } else {
00803       char *BufPtr = Buffer;
00804       while (Amt) {
00805         ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
00806         if (AmtWritten == -1) {
00807           if (errno != EINTR && errno != EAGAIN) {
00808             ::close(inFile);
00809             ::close(outFile);
00810             return MakeErrMsg(ErrMsg, Dest.toString() +
00811               ": can't write destination file");
00812           }
00813         } else {
00814           Amt -= AmtWritten;
00815           BufPtr += AmtWritten;
00816         }
00817       }
00818     }
00819   }
00820   ::close(inFile);
00821   ::close(outFile);
00822   return false;
00823 }
00824 
00825 bool
00826 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
00827   if (reuse_current && !exists())
00828     return false; // File doesn't exist already, just use it!
00829 
00830   // Append an XXXXXX pattern to the end of the file for use with mkstemp,
00831   // mktemp or our own implementation.
00832   char *FNBuffer = (char*) alloca(path.size()+8);
00833     path.copy(FNBuffer,path.size());
00834   if (isDirectory())
00835     strcpy(FNBuffer+path.size(), "/XXXXXX");
00836   else
00837     strcpy(FNBuffer+path.size(), "-XXXXXX");
00838 
00839 #if defined(HAVE_MKSTEMP)
00840   int TempFD;
00841   if ((TempFD = mkstemp(FNBuffer)) == -1)
00842     return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
00843 
00844   // We don't need to hold the temp file descriptor... we will trust that no one
00845   // will overwrite/delete the file before we can open it again.
00846   close(TempFD);
00847 
00848   // Save the name
00849   path = FNBuffer;
00850 #elif defined(HAVE_MKTEMP)
00851   // If we don't have mkstemp, use the old and obsolete mktemp function.
00852   if (mktemp(FNBuffer) == 0)
00853     return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
00854 
00855   // Save the name
00856   path = FNBuffer;
00857 #else
00858   // Okay, looks like we have to do it all by our lonesome.
00859   static unsigned FCounter = 0;
00860   unsigned offset = path.size() + 1;
00861   while ( FCounter < 999999 && exists()) {
00862     sprintf(FNBuffer+offset,"%06u",++FCounter);
00863     path = FNBuffer;
00864   }
00865   if (FCounter > 999999)
00866     return MakeErrMsg(ErrMsg,
00867       path + ": can't make unique filename: too many files");
00868 #endif
00869   return false;
00870 }
00871 
00872 const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
00873   int Flags = MAP_PRIVATE;
00874 #ifdef MAP_FILE
00875   Flags |= MAP_FILE;
00876 #endif
00877   void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
00878   if (BasePtr == MAP_FAILED)
00879     return 0;
00880   return (const char*)BasePtr;
00881 }
00882 
00883 void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
00884   ::munmap((void*)BasePtr, FileSize);
00885 }
00886 
00887 } // end llvm namespace