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"
30 Path::Path(const std::string& unverified_path) : path(unverified_path) {
31 if (unverified_path.empty())
37 ThrowErrno(unverified_path + ": path is not valid");
41 Path::isValid() const {
44 else if (path.length() >= MAXPATHLEN)
46 #if defined(HAVE_REALPATH)
47 char pathname[MAXPATHLEN];
48 if (0 == realpath(path.c_str(), pathname))
49 if (errno != EACCES && errno != EIO && errno != ENOENT && errno != ENOTDIR)
56 Path::GetRootDirectory() {
58 result.setDirectory("/");
63 Path::GetTemporaryDirectory() {
64 #if defined(HAVE_MKDTEMP)
65 // The best way is with mkdtemp but that's not available on many systems,
66 // Linux and FreeBSD have it. Others probably won't.
67 char pathname[MAXPATHLEN];
68 strcpy(pathname,"/tmp/llvm_XXXXXX");
69 if (0 == mkdtemp(pathname))
70 ThrowErrno(std::string(pathname) + ": Can't create temporary directory");
72 result.setDirectory(pathname);
73 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
75 #elif defined(HAVE_MKSTEMP)
76 // If no mkdtemp is available, mkstemp can be used to create a temporary file
77 // which is then removed and created as a directory. We prefer this over
78 // mktemp because of mktemp's inherent security and threading risks. We still
79 // have a slight race condition from the time the temporary file is created to
80 // the time it is re-created as a directoy.
81 char pathname[MAXPATHLEN];
82 strcpy(pathname, "/tmp/llvm_XXXXXX");
84 if (-1 == (fd = mkstemp(pathname)))
85 ThrowErrno(std::string(pathname) + ": Can't create temporary directory");
87 ::unlink(pathname); // start race condition, ignore errors
88 if (-1 == ::mkdir(pathname, S_IRWXU)) // end race condition
89 ThrowErrno(std::string(pathname) + ": Can't create temporary directory");
91 result.setDirectory(pathname);
92 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
94 #elif defined(HAVE_MKTEMP)
95 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
96 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
97 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
98 // the XXXXXX with the pid of the process and a letter. That leads to only
99 // twenty six temporary files that can be generated.
100 char pathname[MAXPATHLEN];
101 strcpy(pathname, "/tmp/llvm_XXXXXX");
102 char *TmpName = ::mktemp(pathname);
104 throw std::string(TmpName) + ": Can't create unique directory name";
105 if (-1 == ::mkdir(TmpName, S_IRWXU))
106 ThrowErrno(std::string(TmpName) + ": Can't create temporary directory");
108 result.setDirectory(TmpName);
109 assert(result.isValid() && "mktemp didn't create a valid pathname!");
112 // This is the worst case implementation. tempnam(3) leaks memory unless its
113 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
114 // issues. The mktemp(3) function doesn't have enough variability in the
115 // temporary name generated. So, we provide our own implementation that
116 // increments an integer from a random number seeded by the current time. This
117 // should be sufficiently unique that we don't have many collisions between
118 // processes. Generally LLVM processes don't run very long and don't use very
119 // many temporary files so this shouldn't be a big issue for LLVM.
120 static time_t num = ::time(0);
121 char pathname[MAXPATHLEN];
124 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
125 } while ( 0 == access(pathname, F_OK ) );
126 if (-1 == ::mkdir(pathname, S_IRWXU))
127 ThrowErrno(std::string(pathname) + ": Can't create temporary directory");
129 result.setDirectory(pathname);
130 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
135 static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
136 const char* at = path;
137 const char* delim = strchr(at, ':');
139 while( delim != 0 ) {
140 std::string tmp(at, size_t(delim-at));
141 if (tmpPath.setDirectory(tmp))
142 if (tmpPath.readable())
143 Paths.push_back(tmpPath);
145 delim = strchr(at, ':');
148 if (tmpPath.setDirectory(std::string(at)))
149 if (tmpPath.readable())
150 Paths.push_back(tmpPath);
155 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
156 #ifdef LTDL_SHLIBPATH_VAR
157 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
159 getPathList(env_var,Paths);
162 // FIXME: Should this look at LD_LIBRARY_PATH too?
163 Paths.push_back(sys::Path("/usr/local/lib/"));
164 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
165 Paths.push_back(sys::Path("/usr/lib/"));
166 Paths.push_back(sys::Path("/lib/"));
170 Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
171 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
173 getPathList(env_var,Paths);
178 if (tmpPath.setDirectory(LLVM_LIBDIR))
179 if (tmpPath.readable())
180 Paths.push_back(tmpPath);
183 GetSystemLibraryPaths(Paths);
187 Path::GetLLVMDefaultConfigDir() {
188 return Path("/etc/llvm/");
192 Path::GetUserHomeDirectory() {
193 const char* home = getenv("HOME");
196 if (result.setDirectory(home))
199 return GetRootDirectory();
203 Path::isFile() const {
204 return (isValid() && path[path.length()-1] != '/');
208 Path::isDirectory() const {
209 return (isValid() && path[path.length()-1] == '/');
213 Path::getBasename() const {
214 // Find the last slash
215 size_t slash = path.rfind('/');
216 if (slash == std::string::npos)
221 return path.substr(slash, path.rfind('.'));
224 bool Path::hasMagicNumber(const std::string &Magic) const {
225 size_t len = Magic.size();
226 assert(len < 1024 && "Request for magic string too long");
227 char* buf = (char*) alloca(1 + len);
228 int fd = ::open(path.c_str(),O_RDONLY);
231 size_t read_len = ::read(fd, buf, len);
239 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
242 assert(len < 1024 && "Request for magic string too long");
243 char* buf = (char*) alloca(1 + len);
244 int fd = ::open(path.c_str(),O_RDONLY);
247 ssize_t bytes_read = ::read(fd, buf, len);
249 if (ssize_t(len) != bytes_read) {
253 Magic.assign(buf,len);
258 Path::isBytecodeFile() const {
261 int fd = ::open(path.c_str(),O_RDONLY);
264 ssize_t bytes_read = ::read(fd, buffer, 4);
269 return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
270 (buffer[3] == 'c' || buffer[3] == 'm'));
274 Path::exists() const {
275 return 0 == access(path.c_str(), F_OK );
279 Path::readable() const {
280 return 0 == access(path.c_str(), F_OK | R_OK );
284 Path::writable() const {
285 return 0 == access(path.c_str(), F_OK | W_OK );
289 Path::executable() const {
290 return 0 == access(path.c_str(), R_OK | X_OK );
294 Path::getLast() const {
295 // Find the last slash
296 size_t pos = path.rfind('/');
298 // Handle the corner cases
299 if (pos == std::string::npos)
302 // If the last character is a slash
303 if (pos == path.length()-1) {
304 // Find the second to last slash
305 size_t pos2 = path.rfind('/', pos-1);
306 if (pos2 == std::string::npos)
307 return path.substr(0,pos);
309 return path.substr(pos2+1,pos-pos2-1);
311 // Return everything after the last slash
312 return path.substr(pos+1);
316 Path::getStatusInfo(StatusInfo& info) const {
318 if (0 != stat(path.c_str(), &buf)) {
319 ThrowErrno(std::string("Can't get status: ")+path);
321 info.fileSize = buf.st_size;
322 info.modTime.fromEpochTime(buf.st_mtime);
323 info.mode = buf.st_mode;
324 info.user = buf.st_uid;
325 info.group = buf.st_gid;
326 info.isDir = S_ISDIR(buf.st_mode);
327 if (info.isDir && path[path.length()-1] != '/')
331 static bool AddPermissionBits(const std::string& Filename, int bits) {
332 // Get the umask value from the operating system. We want to use it
333 // when changing the file's permissions. Since calling umask() sets
334 // the umask and returns its old value, we must call it a second
335 // time to reset it to the user's preference.
336 int mask = umask(0777); // The arg. to umask is arbitrary.
337 umask(mask); // Restore the umask.
339 // Get the file's current mode.
341 if ((stat(Filename.c_str(), &st)) == -1)
344 // Change the file to have whichever permissions bits from 'bits'
345 // that the umask would not disable.
346 if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)
352 void Path::makeReadable() {
353 if (!AddPermissionBits(path,0444))
354 ThrowErrno(path + ": can't make file readable");
357 void Path::makeWriteable() {
358 if (!AddPermissionBits(path,0222))
359 ThrowErrno(path + ": can't make file writable");
362 void Path::makeExecutable() {
363 if (!AddPermissionBits(path,0111))
364 ThrowErrno(path + ": can't make file executable");
368 Path::getDirectoryContents(std::set<Path>& result) const {
371 DIR* direntries = ::opendir(path.c_str());
373 ThrowErrno(path + ": can't open directory");
376 struct dirent* de = ::readdir(direntries);
378 if (de->d_name[0] != '.') {
379 Path aPath(path + (const char*)de->d_name);
381 if (0 != stat(aPath.path.c_str(), &buf))
382 ThrowErrno(aPath.path + ": can't get status");
383 if (S_ISDIR(buf.st_mode))
385 result.insert(aPath);
387 de = ::readdir(direntries);
390 closedir(direntries);
395 Path::setDirectory(const std::string& a_path) {
396 if (a_path.size() == 0)
400 size_t last = a_path.size() -1;
401 if (a_path[last] != '/')
411 Path::setFile(const std::string& a_path) {
412 if (a_path.size() == 0)
416 size_t last = a_path.size() - 1;
417 while (last > 0 && a_path[last] == '/')
428 Path::appendDirectory(const std::string& dir) {
442 Path::elideDirectory() {
445 size_t slashpos = path.rfind('/',path.size());
446 if (slashpos == 0 || slashpos == std::string::npos)
448 if (slashpos == path.size() - 1)
449 slashpos = path.rfind('/',slashpos-1);
450 if (slashpos == std::string::npos)
452 path.erase(slashpos);
457 Path::appendFile(const std::string& file) {
473 size_t slashpos = path.rfind('/',path.size());
474 if (slashpos == std::string::npos)
476 path.erase(slashpos+1);
481 Path::appendSuffix(const std::string& suffix) {
495 Path::elideSuffix() {
496 if (isDirectory()) return false;
497 size_t dotpos = path.rfind('.',path.size());
498 size_t slashpos = path.rfind('/',path.size());
499 if (slashpos != std::string::npos && dotpos != std::string::npos &&
501 path.erase(dotpos, path.size()-dotpos);
509 Path::createDirectory( bool create_parents) {
510 // Make sure we're dealing with a directory
511 if (!isDirectory()) return false;
513 // Get a writeable copy of the path name
514 char pathname[MAXPATHLEN];
515 path.copy(pathname,MAXPATHLEN);
517 // Null-terminate the last component
518 int lastchar = path.length() - 1 ;
519 if (pathname[lastchar] == '/')
520 pathname[lastchar] = 0;
522 pathname[lastchar+1] = 0;
524 // If we're supposed to create intermediate directories
525 if ( create_parents ) {
526 // Find the end of the initial name component
527 char * next = strchr(pathname,'/');
528 if ( pathname[0] == '/')
529 next = strchr(&pathname[1],'/');
531 // Loop through the directory components until we're done
532 while ( next != 0 ) {
534 if (0 != access(pathname, F_OK | R_OK | W_OK))
535 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
536 ThrowErrno(std::string(pathname) + ": Can't create directory");
538 next = strchr(next+1,'/');
543 if (0 != access(pathname, F_OK | R_OK))
544 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
545 ThrowErrno(std::string(pathname) + ": Can't create directory");
551 // Make sure we're dealing with a file
552 if (!isFile()) return false;
555 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
557 ThrowErrno(path + ": Can't create file");
564 Path::createTemporaryFile(bool reuse_current) {
565 // Make sure we're dealing with a file
569 // Make this into a unique file name
570 makeUnique( reuse_current );
573 int outFile = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
582 Path::destroyDirectory(bool remove_contents) const {
583 // Make sure we're dealing with a directory
584 if (!isDirectory()) return false;
586 // If it doesn't exist, we're done.
587 if (!exists()) return true;
589 if (remove_contents) {
590 // Recursively descend the directory to remove its content
591 std::string cmd("/bin/rm -rf ");
595 // Otherwise, try to just remove the one directory
596 char pathname[MAXPATHLEN];
597 path.copy(pathname,MAXPATHLEN);
598 int lastchar = path.length() - 1 ;
599 if (pathname[lastchar] == '/')
600 pathname[lastchar] = 0;
602 pathname[lastchar+1] = 0;
603 if ( 0 != rmdir(pathname))
604 ThrowErrno(std::string(pathname) + ": Can't destroy directory");
610 Path::destroyFile() const {
611 if (!isFile()) return false;
612 if (0 != unlink(path.c_str()))
613 ThrowErrno(path + ": Can't destroy file");
618 Path::renameFile(const Path& newName) {
619 if (!isFile()) return false;
620 if (0 != rename(path.c_str(), newName.c_str()))
621 ThrowErrno(std::string("can't rename ") + path + " as " +
627 Path::setStatusInfo(const StatusInfo& si) const {
628 if (!isFile()) return false;
630 utb.actime = si.modTime.toPosixTime();
631 utb.modtime = utb.actime;
632 if (0 != ::utime(path.c_str(),&utb))
633 ThrowErrno(path + ": can't set file modification time");
634 if (0 != ::chmod(path.c_str(),si.mode))
635 ThrowErrno(path + ": can't set mode");
640 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src) {
644 inFile = ::open(Src.c_str(), O_RDONLY);
646 ThrowErrno("Cannnot open source file to copy: " + Src.toString());
648 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
650 ThrowErrno("Cannnot create destination file for copy: " +Dest.toString());
652 char Buffer[16*1024];
653 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
655 if (errno != EINTR && errno != EAGAIN)
656 ThrowErrno("Can't read source file: " + Src.toString());
658 char *BufPtr = Buffer;
660 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
661 if (AmtWritten == -1) {
662 if (errno != EINTR && errno != EAGAIN)
663 ThrowErrno("Can't write destination file: " + Dest.toString());
666 BufPtr += AmtWritten;
683 Path::makeUnique(bool reuse_current) {
684 if (reuse_current && !exists())
685 return; // File doesn't exist already, just use it!
687 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
688 // mktemp or our own implementation.
689 char *FNBuffer = (char*) alloca(path.size()+8);
690 path.copy(FNBuffer,path.size());
691 strcpy(FNBuffer+path.size(), "-XXXXXX");
693 #if defined(HAVE_MKSTEMP)
695 if ((TempFD = mkstemp(FNBuffer)) == -1) {
696 ThrowErrno("Cannot make unique filename for '" + path + "'");
699 // We don't need to hold the temp file descriptor... we will trust that no one
700 // will overwrite/delete the file before we can open it again.
705 #elif defined(HAVE_MKTEMP)
706 // If we don't have mkstemp, use the old and obsolete mktemp function.
707 if (mktemp(FNBuffer) == 0) {
708 ThrowErrno("Cannot make unique filename for '" + path + "'");
714 // Okay, looks like we have to do it all by our lonesome.
715 static unsigned FCounter = 0;
716 unsigned offset = path.size() + 1;
717 while ( FCounter < 999999 && exists()) {
718 sprintf(FNBuffer+offset,"%06u",++FCounter);
721 if (FCounter > 999999)
722 throw std::string("Cannot make unique filename for '" + path + "'");