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>
50 // Put in a hack for Cygwin which falsely reports that the mkdtemp function
51 // is available when it is not.
59 Path::Path(const std::string& unverified_path) : path(unverified_path) {
60 if (unverified_path.empty())
66 ThrowErrno(unverified_path + ": path is not valid");
70 Path::isValid() const {
73 else if (path.length() >= MAXPATHLEN)
75 #if defined(HAVE_REALPATH)
76 char pathname[MAXPATHLEN];
77 if (0 == realpath(path.c_str(), pathname))
78 if (errno != EACCES && errno != EIO && errno != ENOENT && errno != ENOTDIR)
85 Path::GetRootDirectory() {
87 result.setDirectory("/");
92 Path::GetTemporaryDirectory() {
93 #if defined(HAVE_MKDTEMP)
94 // The best way is with mkdtemp but that's not available on many systems,
95 // Linux and FreeBSD have it. Others probably won't.
96 char pathname[MAXPATHLEN];
97 strcpy(pathname,"/tmp/llvm_XXXXXX");
98 if (0 == mkdtemp(pathname))
99 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
101 result.setDirectory(pathname);
102 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
104 #elif defined(HAVE_MKSTEMP)
105 // If no mkdtemp is available, mkstemp can be used to create a temporary file
106 // which is then removed and created as a directory. We prefer this over
107 // mktemp because of mktemp's inherent security and threading risks. We still
108 // have a slight race condition from the time the temporary file is created to
109 // the time it is re-created as a directoy.
110 char pathname[MAXPATHLEN];
111 strcpy(pathname, "/tmp/llvm_XXXXXX");
113 if (-1 == (fd = mkstemp(pathname)))
114 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
116 ::unlink(pathname); // start race condition, ignore errors
117 if (-1 == ::mkdir(pathname, S_IRWXU)) // end race condition
118 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
120 result.setDirectory(pathname);
121 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
123 #elif defined(HAVE_MKTEMP)
124 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
125 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
126 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
127 // the XXXXXX with the pid of the process and a letter. That leads to only
128 // twenty six temporary files that can be generated.
129 char pathname[MAXPATHLEN];
130 strcpy(pathname, "/tmp/llvm_XXXXXX");
131 char *TmpName = ::mktemp(pathname);
133 ThrowErrno(std::string(TmpName) + ": can't create unique directory name");
134 if (-1 == ::mkdir(TmpName, S_IRWXU))
135 ThrowErrno(std::string(TmpName) + ": can't create temporary directory");
137 result.setDirectory(TmpName);
138 assert(result.isValid() && "mktemp didn't create a valid pathname!");
141 // This is the worst case implementation. tempnam(3) leaks memory unless its
142 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
143 // issues. The mktemp(3) function doesn't have enough variability in the
144 // temporary name generated. So, we provide our own implementation that
145 // increments an integer from a random number seeded by the current time. This
146 // should be sufficiently unique that we don't have many collisions between
147 // processes. Generally LLVM processes don't run very long and don't use very
148 // many temporary files so this shouldn't be a big issue for LLVM.
149 static time_t num = ::time(0);
150 char pathname[MAXPATHLEN];
153 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
154 } while ( 0 == access(pathname, F_OK ) );
155 if (-1 == ::mkdir(pathname, S_IRWXU))
156 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
158 result.setDirectory(pathname);
159 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
164 static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
165 const char* at = path;
166 const char* delim = strchr(at, ':');
168 while( delim != 0 ) {
169 std::string tmp(at, size_t(delim-at));
170 if (tmpPath.setDirectory(tmp))
171 if (tmpPath.readable())
172 Paths.push_back(tmpPath);
174 delim = strchr(at, ':');
177 if (tmpPath.setDirectory(std::string(at)))
178 if (tmpPath.readable())
179 Paths.push_back(tmpPath);
184 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
185 #ifdef LTDL_SHLIBPATH_VAR
186 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
188 getPathList(env_var,Paths);
191 // FIXME: Should this look at LD_LIBRARY_PATH too?
192 Paths.push_back(sys::Path("/usr/local/lib/"));
193 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
194 Paths.push_back(sys::Path("/usr/lib/"));
195 Paths.push_back(sys::Path("/lib/"));
199 Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
200 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
202 getPathList(env_var,Paths);
207 if (tmpPath.setDirectory(LLVM_LIBDIR))
208 if (tmpPath.readable())
209 Paths.push_back(tmpPath);
212 GetSystemLibraryPaths(Paths);
216 Path::GetLLVMDefaultConfigDir() {
217 return Path("/etc/llvm/");
221 Path::GetUserHomeDirectory() {
222 const char* home = getenv("HOME");
225 if (result.setDirectory(home))
228 return GetRootDirectory();
232 Path::isFile() const {
233 return (isValid() && path[path.length()-1] != '/');
237 Path::isDirectory() const {
238 return (isValid() && path[path.length()-1] == '/');
242 Path::getBasename() const {
243 // Find the last slash
244 size_t slash = path.rfind('/');
245 if (slash == std::string::npos)
250 return path.substr(slash, path.rfind('.'));
253 bool Path::hasMagicNumber(const std::string &Magic) const {
254 size_t len = Magic.size();
255 assert(len < 1024 && "Request for magic string too long");
256 char* buf = (char*) alloca(1 + len);
257 int fd = ::open(path.c_str(),O_RDONLY);
260 size_t read_len = ::read(fd, buf, len);
268 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
271 assert(len < 1024 && "Request for magic string too long");
272 char* buf = (char*) alloca(1 + len);
273 int fd = ::open(path.c_str(),O_RDONLY);
276 ssize_t bytes_read = ::read(fd, buf, len);
278 if (ssize_t(len) != bytes_read) {
282 Magic.assign(buf,len);
287 Path::isBytecodeFile() const {
290 int fd = ::open(path.c_str(),O_RDONLY);
293 ssize_t bytes_read = ::read(fd, buffer, 4);
298 return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
299 (buffer[3] == 'c' || buffer[3] == 'm'));
303 Path::exists() const {
304 return 0 == access(path.c_str(), F_OK );
308 Path::readable() const {
309 return 0 == access(path.c_str(), F_OK | R_OK );
313 Path::writable() const {
314 return 0 == access(path.c_str(), F_OK | W_OK );
318 Path::executable() const {
320 int r = stat(path.c_str(), &st);
321 if (r != 0 || !S_ISREG(st.st_mode))
323 return 0 == access(path.c_str(), R_OK | X_OK );
327 Path::getLast() const {
328 // Find the last slash
329 size_t pos = path.rfind('/');
331 // Handle the corner cases
332 if (pos == std::string::npos)
335 // If the last character is a slash
336 if (pos == path.length()-1) {
337 // Find the second to last slash
338 size_t pos2 = path.rfind('/', pos-1);
339 if (pos2 == std::string::npos)
340 return path.substr(0,pos);
342 return path.substr(pos2+1,pos-pos2-1);
344 // Return everything after the last slash
345 return path.substr(pos+1);
349 Path::getStatusInfo(StatusInfo& info) const {
351 if (0 != stat(path.c_str(), &buf)) {
352 ThrowErrno(path + ": can't determine type of path object: ");
354 info.fileSize = buf.st_size;
355 info.modTime.fromEpochTime(buf.st_mtime);
356 info.mode = buf.st_mode;
357 info.user = buf.st_uid;
358 info.group = buf.st_gid;
359 info.isDir = S_ISDIR(buf.st_mode);
360 if (info.isDir && path[path.length()-1] != '/')
364 static bool AddPermissionBits(const std::string& Filename, int bits) {
365 // Get the umask value from the operating system. We want to use it
366 // when changing the file's permissions. Since calling umask() sets
367 // the umask and returns its old value, we must call it a second
368 // time to reset it to the user's preference.
369 int mask = umask(0777); // The arg. to umask is arbitrary.
370 umask(mask); // Restore the umask.
372 // Get the file's current mode.
374 if ((stat(Filename.c_str(), &st)) == -1)
377 // Change the file to have whichever permissions bits from 'bits'
378 // that the umask would not disable.
379 if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)
385 void Path::makeReadable() {
386 if (!AddPermissionBits(path,0444))
387 ThrowErrno(path + ": can't make file readable");
390 void Path::makeWriteable() {
391 if (!AddPermissionBits(path,0222))
392 ThrowErrno(path + ": can't make file writable");
395 void Path::makeExecutable() {
396 if (!AddPermissionBits(path,0111))
397 ThrowErrno(path + ": can't make file executable");
401 Path::getDirectoryContents(std::set<Path>& result) const {
404 DIR* direntries = ::opendir(path.c_str());
406 ThrowErrno(path + ": can't open directory");
409 struct dirent* de = ::readdir(direntries);
410 for ( ; de != 0; de = ::readdir(direntries)) {
411 if (de->d_name[0] != '.') {
412 Path aPath(path + (const char*)de->d_name);
414 if (0 != stat(aPath.path.c_str(), &buf)) {
415 int stat_errno = errno;
417 if (0 == lstat(aPath.path.c_str(), &st) && S_ISLNK(st.st_mode))
418 continue; // dangling symlink -- ignore
419 ThrowErrno(aPath.path +
420 ": can't determine file object type", stat_errno);
422 if (S_ISDIR(buf.st_mode))
424 result.insert(aPath);
428 closedir(direntries);
433 Path::setDirectory(const std::string& a_path) {
434 if (a_path.size() == 0)
438 size_t last = a_path.size() -1;
439 if (a_path[last] != '/')
449 Path::setFile(const std::string& a_path) {
450 if (a_path.size() == 0)
454 size_t last = a_path.size() - 1;
455 while (last > 0 && a_path[last] == '/')
466 Path::appendDirectory(const std::string& dir) {
480 Path::elideDirectory() {
483 size_t slashpos = path.rfind('/',path.size());
484 if (slashpos == 0 || slashpos == std::string::npos)
486 if (slashpos == path.size() - 1)
487 slashpos = path.rfind('/',slashpos-1);
488 if (slashpos == std::string::npos)
490 path.erase(slashpos);
495 Path::appendFile(const std::string& file) {
511 size_t slashpos = path.rfind('/',path.size());
512 if (slashpos == std::string::npos)
514 path.erase(slashpos+1);
519 Path::appendSuffix(const std::string& suffix) {
533 Path::elideSuffix() {
534 if (isDirectory()) return false;
535 size_t dotpos = path.rfind('.',path.size());
536 size_t slashpos = path.rfind('/',path.size());
537 if (slashpos != std::string::npos && dotpos != std::string::npos &&
539 path.erase(dotpos, path.size()-dotpos);
547 Path::createDirectory( bool create_parents) {
548 // Make sure we're dealing with a directory
549 if (!isDirectory()) return false;
551 // Get a writeable copy of the path name
552 char pathname[MAXPATHLEN];
553 path.copy(pathname,MAXPATHLEN);
555 // Null-terminate the last component
556 int lastchar = path.length() - 1 ;
557 if (pathname[lastchar] == '/')
558 pathname[lastchar] = 0;
560 pathname[lastchar+1] = 0;
562 // If we're supposed to create intermediate directories
563 if ( create_parents ) {
564 // Find the end of the initial name component
565 char * next = strchr(pathname,'/');
566 if ( pathname[0] == '/')
567 next = strchr(&pathname[1],'/');
569 // Loop through the directory components until we're done
570 while ( next != 0 ) {
572 if (0 != access(pathname, F_OK | R_OK | W_OK))
573 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
574 ThrowErrno(std::string(pathname) + ": can't create directory");
576 next = strchr(next+1,'/');
581 if (0 != access(pathname, F_OK | R_OK))
582 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
583 ThrowErrno(std::string(pathname) + ": can't create directory");
589 // Make sure we're dealing with a file
590 if (!isFile()) return false;
593 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
595 ThrowErrno(path + ": can't create file");
602 Path::createTemporaryFile(bool reuse_current) {
603 // Make sure we're dealing with a file
607 // Make this into a unique file name
608 makeUnique( reuse_current );
611 int outFile = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
620 Path::destroyDirectory(bool remove_contents) const {
621 // Make sure we're dealing with a directory
622 if (!isDirectory()) return false;
624 // If it doesn't exist, we're done.
625 if (!exists()) return true;
627 if (remove_contents) {
628 // Recursively descend the directory to remove its content
629 std::string cmd("/bin/rm -rf ");
633 // Otherwise, try to just remove the one directory
634 char pathname[MAXPATHLEN];
635 path.copy(pathname,MAXPATHLEN);
636 int lastchar = path.length() - 1 ;
637 if (pathname[lastchar] == '/')
638 pathname[lastchar] = 0;
640 pathname[lastchar+1] = 0;
641 if ( 0 != rmdir(pathname))
642 ThrowErrno(std::string(pathname) + ": can't destroy directory");
648 Path::destroyFile() const {
649 if (!isFile()) return false;
650 if (0 != unlink(path.c_str()))
651 ThrowErrno(path + ": can't destroy file");
656 Path::renameFile(const Path& newName) {
657 if (!isFile()) return false;
658 if (0 != rename(path.c_str(), newName.c_str()))
659 ThrowErrno(std::string("can't rename '") + path + "' as '" +
660 newName.toString() + "' ");
665 Path::setStatusInfo(const StatusInfo& si) const {
666 if (!isFile()) return false;
668 utb.actime = si.modTime.toPosixTime();
669 utb.modtime = utb.actime;
670 if (0 != ::utime(path.c_str(),&utb))
671 ThrowErrno(path + ": can't set file modification time");
672 if (0 != ::chmod(path.c_str(),si.mode))
673 ThrowErrno(path + ": can't set mode");
678 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src) {
682 inFile = ::open(Src.c_str(), O_RDONLY);
684 ThrowErrno(Src.toString() + ": can't open source file to copy: ");
686 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
688 ThrowErrno(Dest.toString() +": can't create destination file for copy: ");
690 char Buffer[16*1024];
691 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
693 if (errno != EINTR && errno != EAGAIN)
694 ThrowErrno(Src.toString()+": can't read source file: ");
696 char *BufPtr = Buffer;
698 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
699 if (AmtWritten == -1) {
700 if (errno != EINTR && errno != EAGAIN)
701 ThrowErrno(Dest.toString() + ": can't write destination file: ");
704 BufPtr += AmtWritten;
721 Path::makeUnique(bool reuse_current) {
722 if (reuse_current && !exists())
723 return; // File doesn't exist already, just use it!
725 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
726 // mktemp or our own implementation.
727 char *FNBuffer = (char*) alloca(path.size()+8);
728 path.copy(FNBuffer,path.size());
729 strcpy(FNBuffer+path.size(), "-XXXXXX");
731 #if defined(HAVE_MKSTEMP)
733 if ((TempFD = mkstemp(FNBuffer)) == -1) {
734 ThrowErrno(path + ": can't make unique filename");
737 // We don't need to hold the temp file descriptor... we will trust that no one
738 // will overwrite/delete the file before we can open it again.
743 #elif defined(HAVE_MKTEMP)
744 // If we don't have mkstemp, use the old and obsolete mktemp function.
745 if (mktemp(FNBuffer) == 0) {
746 ThrowErrno(path + ": can't make unique filename");
752 // Okay, looks like we have to do it all by our lonesome.
753 static unsigned FCounter = 0;
754 unsigned offset = path.size() + 1;
755 while ( FCounter < 999999 && exists()) {
756 sprintf(FNBuffer+offset,"%06u",++FCounter);
759 if (FCounter > 999999)
760 throw std::string(path + ": can't make unique filename: too many files");