1 //===- llvm/System/Unix/Path.cpp - Unix Path Implementation -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Unix specific portion of the Path class.
12 //===----------------------------------------------------------------------===//
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic UNIX code that
16 //=== is guaranteed to work on *all* UNIX variants.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Config/alloca.h"
35 # define NAMLEN(dirent) strlen((dirent)->d_name)
37 # define dirent direct
38 # define NAMLEN(dirent) (dirent)->d_namlen
40 # include <sys/ndir.h>
54 Path::Path(const std::string& unverified_path) : path(unverified_path) {
55 if (unverified_path.empty())
61 ThrowErrno(unverified_path + ": path is not valid");
65 Path::isValid() const {
68 else if (path.length() >= MAXPATHLEN)
70 #if defined(HAVE_REALPATH)
71 char pathname[MAXPATHLEN];
72 if (0 == realpath(path.c_str(), pathname))
73 if (errno != EACCES && errno != EIO && errno != ENOENT && errno != ENOTDIR)
80 Path::GetRootDirectory() {
82 result.setDirectory("/");
87 Path::GetTemporaryDirectory() {
88 #if defined(HAVE_MKDTEMP)
89 // The best way is with mkdtemp but that's not available on many systems,
90 // Linux and FreeBSD have it. Others probably won't.
91 char pathname[MAXPATHLEN];
92 strcpy(pathname,"/tmp/llvm_XXXXXX");
93 if (0 == mkdtemp(pathname))
94 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
96 result.setDirectory(pathname);
97 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
99 #elif defined(HAVE_MKSTEMP)
100 // If no mkdtemp is available, mkstemp can be used to create a temporary file
101 // which is then removed and created as a directory. We prefer this over
102 // mktemp because of mktemp's inherent security and threading risks. We still
103 // have a slight race condition from the time the temporary file is created to
104 // the time it is re-created as a directoy.
105 char pathname[MAXPATHLEN];
106 strcpy(pathname, "/tmp/llvm_XXXXXX");
108 if (-1 == (fd = mkstemp(pathname)))
109 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
111 ::unlink(pathname); // start race condition, ignore errors
112 if (-1 == ::mkdir(pathname, S_IRWXU)) // end race condition
113 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
115 result.setDirectory(pathname);
116 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
118 #elif defined(HAVE_MKTEMP)
119 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
120 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
121 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
122 // the XXXXXX with the pid of the process and a letter. That leads to only
123 // twenty six temporary files that can be generated.
124 char pathname[MAXPATHLEN];
125 strcpy(pathname, "/tmp/llvm_XXXXXX");
126 char *TmpName = ::mktemp(pathname);
128 ThrowErrno(std::string(TmpName) + ": can't create unique directory name");
129 if (-1 == ::mkdir(TmpName, S_IRWXU))
130 ThrowErrno(std::string(TmpName) + ": can't create temporary directory");
132 result.setDirectory(TmpName);
133 assert(result.isValid() && "mktemp didn't create a valid pathname!");
136 // This is the worst case implementation. tempnam(3) leaks memory unless its
137 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
138 // issues. The mktemp(3) function doesn't have enough variability in the
139 // temporary name generated. So, we provide our own implementation that
140 // increments an integer from a random number seeded by the current time. This
141 // should be sufficiently unique that we don't have many collisions between
142 // processes. Generally LLVM processes don't run very long and don't use very
143 // many temporary files so this shouldn't be a big issue for LLVM.
144 static time_t num = ::time(0);
145 char pathname[MAXPATHLEN];
148 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
149 } while ( 0 == access(pathname, F_OK ) );
150 if (-1 == ::mkdir(pathname, S_IRWXU))
151 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
153 result.setDirectory(pathname);
154 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
159 static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
160 const char* at = path;
161 const char* delim = strchr(at, ':');
163 while( delim != 0 ) {
164 std::string tmp(at, size_t(delim-at));
165 if (tmpPath.setDirectory(tmp))
166 if (tmpPath.readable())
167 Paths.push_back(tmpPath);
169 delim = strchr(at, ':');
172 if (tmpPath.setDirectory(std::string(at)))
173 if (tmpPath.readable())
174 Paths.push_back(tmpPath);
179 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
180 #ifdef LTDL_SHLIBPATH_VAR
181 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
183 getPathList(env_var,Paths);
186 // FIXME: Should this look at LD_LIBRARY_PATH too?
187 Paths.push_back(sys::Path("/usr/local/lib/"));
188 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
189 Paths.push_back(sys::Path("/usr/lib/"));
190 Paths.push_back(sys::Path("/lib/"));
194 Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
195 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
197 getPathList(env_var,Paths);
202 if (tmpPath.setDirectory(LLVM_LIBDIR))
203 if (tmpPath.readable())
204 Paths.push_back(tmpPath);
207 GetSystemLibraryPaths(Paths);
211 Path::GetLLVMDefaultConfigDir() {
212 return Path("/etc/llvm/");
216 Path::GetUserHomeDirectory() {
217 const char* home = getenv("HOME");
220 if (result.setDirectory(home))
223 return GetRootDirectory();
227 Path::isFile() const {
228 return (isValid() && path[path.length()-1] != '/');
232 Path::isDirectory() const {
233 return (isValid() && path[path.length()-1] == '/');
237 Path::getBasename() const {
238 // Find the last slash
239 size_t slash = path.rfind('/');
240 if (slash == std::string::npos)
245 return path.substr(slash, path.rfind('.'));
248 bool Path::hasMagicNumber(const std::string &Magic) const {
249 size_t len = Magic.size();
250 assert(len < 1024 && "Request for magic string too long");
251 char* buf = (char*) alloca(1 + len);
252 int fd = ::open(path.c_str(),O_RDONLY);
255 size_t read_len = ::read(fd, buf, len);
263 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
266 assert(len < 1024 && "Request for magic string too long");
267 char* buf = (char*) alloca(1 + len);
268 int fd = ::open(path.c_str(),O_RDONLY);
271 ssize_t bytes_read = ::read(fd, buf, len);
273 if (ssize_t(len) != bytes_read) {
277 Magic.assign(buf,len);
282 Path::isBytecodeFile() const {
285 int fd = ::open(path.c_str(),O_RDONLY);
288 ssize_t bytes_read = ::read(fd, buffer, 4);
293 return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
294 (buffer[3] == 'c' || buffer[3] == 'm'));
298 Path::exists() const {
299 return 0 == access(path.c_str(), F_OK );
303 Path::readable() const {
304 return 0 == access(path.c_str(), F_OK | R_OK );
308 Path::writable() const {
309 return 0 == access(path.c_str(), F_OK | W_OK );
313 Path::executable() const {
315 int r = stat(path.c_str(), &st);
316 if (r != 0 || !S_ISREG(st.st_mode))
318 return 0 == access(path.c_str(), R_OK | X_OK );
322 Path::getLast() const {
323 // Find the last slash
324 size_t pos = path.rfind('/');
326 // Handle the corner cases
327 if (pos == std::string::npos)
330 // If the last character is a slash
331 if (pos == path.length()-1) {
332 // Find the second to last slash
333 size_t pos2 = path.rfind('/', pos-1);
334 if (pos2 == std::string::npos)
335 return path.substr(0,pos);
337 return path.substr(pos2+1,pos-pos2-1);
339 // Return everything after the last slash
340 return path.substr(pos+1);
344 Path::getStatusInfo(StatusInfo& info) const {
346 if (0 != stat(path.c_str(), &buf)) {
347 ThrowErrno(path + ": can't determine type of path object: ");
349 info.fileSize = buf.st_size;
350 info.modTime.fromEpochTime(buf.st_mtime);
351 info.mode = buf.st_mode;
352 info.user = buf.st_uid;
353 info.group = buf.st_gid;
354 info.isDir = S_ISDIR(buf.st_mode);
355 if (info.isDir && path[path.length()-1] != '/')
359 static bool AddPermissionBits(const std::string& Filename, int bits) {
360 // Get the umask value from the operating system. We want to use it
361 // when changing the file's permissions. Since calling umask() sets
362 // the umask and returns its old value, we must call it a second
363 // time to reset it to the user's preference.
364 int mask = umask(0777); // The arg. to umask is arbitrary.
365 umask(mask); // Restore the umask.
367 // Get the file's current mode.
369 if ((stat(Filename.c_str(), &st)) == -1)
372 // Change the file to have whichever permissions bits from 'bits'
373 // that the umask would not disable.
374 if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)
380 void Path::makeReadable() {
381 if (!AddPermissionBits(path,0444))
382 ThrowErrno(path + ": can't make file readable");
385 void Path::makeWriteable() {
386 if (!AddPermissionBits(path,0222))
387 ThrowErrno(path + ": can't make file writable");
390 void Path::makeExecutable() {
391 if (!AddPermissionBits(path,0111))
392 ThrowErrno(path + ": can't make file executable");
396 Path::getDirectoryContents(std::set<Path>& result) const {
399 DIR* direntries = ::opendir(path.c_str());
401 ThrowErrno(path + ": can't open directory");
404 struct dirent* de = ::readdir(direntries);
405 for ( ; de != 0; de = ::readdir(direntries)) {
406 if (de->d_name[0] != '.') {
407 Path aPath(path + (const char*)de->d_name);
409 if (0 != stat(aPath.path.c_str(), &buf)) {
410 int stat_errno = errno;
412 if (0 == lstat(aPath.path.c_str(), &st) && S_ISLNK(st.st_mode))
413 continue; // dangling symlink -- ignore
414 ThrowErrno(aPath.path +
415 ": can't determine file object type", stat_errno);
417 if (S_ISDIR(buf.st_mode))
419 result.insert(aPath);
423 closedir(direntries);
428 Path::setDirectory(const std::string& a_path) {
429 if (a_path.size() == 0)
433 size_t last = a_path.size() -1;
434 if (a_path[last] != '/')
444 Path::setFile(const std::string& a_path) {
445 if (a_path.size() == 0)
449 size_t last = a_path.size() - 1;
450 while (last > 0 && a_path[last] == '/')
461 Path::appendDirectory(const std::string& dir) {
475 Path::elideDirectory() {
478 size_t slashpos = path.rfind('/',path.size());
479 if (slashpos == 0 || slashpos == std::string::npos)
481 if (slashpos == path.size() - 1)
482 slashpos = path.rfind('/',slashpos-1);
483 if (slashpos == std::string::npos)
485 path.erase(slashpos);
490 Path::appendFile(const std::string& file) {
506 size_t slashpos = path.rfind('/',path.size());
507 if (slashpos == std::string::npos)
509 path.erase(slashpos+1);
514 Path::appendSuffix(const std::string& suffix) {
528 Path::elideSuffix() {
529 if (isDirectory()) return false;
530 size_t dotpos = path.rfind('.',path.size());
531 size_t slashpos = path.rfind('/',path.size());
532 if (slashpos != std::string::npos && dotpos != std::string::npos &&
534 path.erase(dotpos, path.size()-dotpos);
542 Path::createDirectory( bool create_parents) {
543 // Make sure we're dealing with a directory
544 if (!isDirectory()) return false;
546 // Get a writeable copy of the path name
547 char pathname[MAXPATHLEN];
548 path.copy(pathname,MAXPATHLEN);
550 // Null-terminate the last component
551 int lastchar = path.length() - 1 ;
552 if (pathname[lastchar] == '/')
553 pathname[lastchar] = 0;
555 pathname[lastchar+1] = 0;
557 // If we're supposed to create intermediate directories
558 if ( create_parents ) {
559 // Find the end of the initial name component
560 char * next = strchr(pathname,'/');
561 if ( pathname[0] == '/')
562 next = strchr(&pathname[1],'/');
564 // Loop through the directory components until we're done
565 while ( next != 0 ) {
567 if (0 != access(pathname, F_OK | R_OK | W_OK))
568 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
569 ThrowErrno(std::string(pathname) + ": can't create directory");
571 next = strchr(next+1,'/');
576 if (0 != access(pathname, F_OK | R_OK))
577 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
578 ThrowErrno(std::string(pathname) + ": can't create directory");
584 // Make sure we're dealing with a file
585 if (!isFile()) return false;
588 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
590 ThrowErrno(path + ": can't create file");
597 Path::createTemporaryFile(bool reuse_current) {
598 // Make sure we're dealing with a file
602 // Make this into a unique file name
603 makeUnique( reuse_current );
606 int outFile = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
615 Path::destroyDirectory(bool remove_contents) const {
616 // Make sure we're dealing with a directory
617 if (!isDirectory()) return false;
619 // If it doesn't exist, we're done.
620 if (!exists()) return true;
622 if (remove_contents) {
623 // Recursively descend the directory to remove its content
624 std::string cmd("/bin/rm -rf ");
628 // Otherwise, try to just remove the one directory
629 char pathname[MAXPATHLEN];
630 path.copy(pathname,MAXPATHLEN);
631 int lastchar = path.length() - 1 ;
632 if (pathname[lastchar] == '/')
633 pathname[lastchar] = 0;
635 pathname[lastchar+1] = 0;
636 if ( 0 != rmdir(pathname))
637 ThrowErrno(std::string(pathname) + ": can't destroy directory");
643 Path::destroyFile() const {
644 if (!isFile()) return false;
645 if (0 != unlink(path.c_str()))
646 ThrowErrno(path + ": can't destroy file");
651 Path::renameFile(const Path& newName) {
652 if (!isFile()) return false;
653 if (0 != rename(path.c_str(), newName.c_str()))
654 ThrowErrno(std::string("can't rename '") + path + "' as '" +
655 newName.toString() + "' ");
660 Path::setStatusInfo(const StatusInfo& si) const {
661 if (!isFile()) return false;
663 utb.actime = si.modTime.toPosixTime();
664 utb.modtime = utb.actime;
665 if (0 != ::utime(path.c_str(),&utb))
666 ThrowErrno(path + ": can't set file modification time");
667 if (0 != ::chmod(path.c_str(),si.mode))
668 ThrowErrno(path + ": can't set mode");
673 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src) {
677 inFile = ::open(Src.c_str(), O_RDONLY);
679 ThrowErrno(Src.toString() + ": can't open source file to copy: ");
681 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
683 ThrowErrno(Dest.toString() +": can't create destination file for copy: ");
685 char Buffer[16*1024];
686 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
688 if (errno != EINTR && errno != EAGAIN)
689 ThrowErrno(Src.toString()+": can't read source file: ");
691 char *BufPtr = Buffer;
693 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
694 if (AmtWritten == -1) {
695 if (errno != EINTR && errno != EAGAIN)
696 ThrowErrno(Dest.toString() + ": can't write destination file: ");
699 BufPtr += AmtWritten;
716 Path::makeUnique(bool reuse_current) {
717 if (reuse_current && !exists())
718 return; // File doesn't exist already, just use it!
720 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
721 // mktemp or our own implementation.
722 char *FNBuffer = (char*) alloca(path.size()+8);
723 path.copy(FNBuffer,path.size());
724 strcpy(FNBuffer+path.size(), "-XXXXXX");
726 #if defined(HAVE_MKSTEMP)
728 if ((TempFD = mkstemp(FNBuffer)) == -1) {
729 ThrowErrno(path + ": can't make unique filename");
732 // We don't need to hold the temp file descriptor... we will trust that no one
733 // will overwrite/delete the file before we can open it again.
738 #elif defined(HAVE_MKTEMP)
739 // If we don't have mkstemp, use the old and obsolete mktemp function.
740 if (mktemp(FNBuffer) == 0) {
741 ThrowErrno(path + ": can't make unique filename");
747 // Okay, looks like we have to do it all by our lonesome.
748 static unsigned FCounter = 0;
749 unsigned offset = path.size() + 1;
750 while ( FCounter < 999999 && exists()) {
751 sprintf(FNBuffer+offset,"%06u",++FCounter);
754 if (FCounter > 999999)
755 throw std::string(path + ": can't make unique filename: too many files");