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 {
71 // Check some obvious things
74 else if (path.length() >= MAXPATHLEN)
77 // Check that the characters are ascii chars
78 size_t len = path.length();
80 while (i < len && isascii(path[i]))
86 Path::GetRootDirectory() {
93 Path::GetTemporaryDirectory() {
94 #if defined(HAVE_MKDTEMP)
95 // The best way is with mkdtemp but that's not available on many systems,
96 // Linux and FreeBSD have it. Others probably won't.
97 char pathname[MAXPATHLEN];
98 strcpy(pathname,"/tmp/llvm_XXXXXX");
99 if (0 == mkdtemp(pathname))
100 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
102 result.set(pathname);
103 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
105 #elif defined(HAVE_MKSTEMP)
106 // If no mkdtemp is available, mkstemp can be used to create a temporary file
107 // which is then removed and created as a directory. We prefer this over
108 // mktemp because of mktemp's inherent security and threading risks. We still
109 // have a slight race condition from the time the temporary file is created to
110 // the time it is re-created as a directoy.
111 char pathname[MAXPATHLEN];
112 strcpy(pathname, "/tmp/llvm_XXXXXX");
114 if (-1 == (fd = mkstemp(pathname)))
115 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
117 ::unlink(pathname); // start race condition, ignore errors
118 if (-1 == ::mkdir(pathname, S_IRWXU)) // end race condition
119 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
121 result.set(pathname);
122 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
124 #elif defined(HAVE_MKTEMP)
125 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
126 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
127 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
128 // the XXXXXX with the pid of the process and a letter. That leads to only
129 // twenty six temporary files that can be generated.
130 char pathname[MAXPATHLEN];
131 strcpy(pathname, "/tmp/llvm_XXXXXX");
132 char *TmpName = ::mktemp(pathname);
134 ThrowErrno(std::string(TmpName) + ": can't create unique directory name");
135 if (-1 == ::mkdir(TmpName, S_IRWXU))
136 ThrowErrno(std::string(TmpName) + ": can't create temporary directory");
139 assert(result.isValid() && "mktemp didn't create a valid pathname!");
142 // This is the worst case implementation. tempnam(3) leaks memory unless its
143 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
144 // issues. The mktemp(3) function doesn't have enough variability in the
145 // temporary name generated. So, we provide our own implementation that
146 // increments an integer from a random number seeded by the current time. This
147 // should be sufficiently unique that we don't have many collisions between
148 // processes. Generally LLVM processes don't run very long and don't use very
149 // many temporary files so this shouldn't be a big issue for LLVM.
150 static time_t num = ::time(0);
151 char pathname[MAXPATHLEN];
154 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
155 } while ( 0 == access(pathname, F_OK ) );
156 if (-1 == ::mkdir(pathname, S_IRWXU))
157 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
159 result.set(pathname);
160 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
165 static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
166 const char* at = path;
167 const char* delim = strchr(at, ':');
169 while( delim != 0 ) {
170 std::string tmp(at, size_t(delim-at));
171 if (tmpPath.set(tmp))
172 if (tmpPath.canRead())
173 Paths.push_back(tmpPath);
175 delim = strchr(at, ':');
178 if (tmpPath.set(std::string(at)))
179 if (tmpPath.canRead())
180 Paths.push_back(tmpPath);
185 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
186 #ifdef LTDL_SHLIBPATH_VAR
187 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
189 getPathList(env_var,Paths);
192 // FIXME: Should this look at LD_LIBRARY_PATH too?
193 Paths.push_back(sys::Path("/usr/local/lib/"));
194 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
195 Paths.push_back(sys::Path("/usr/lib/"));
196 Paths.push_back(sys::Path("/lib/"));
200 Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
201 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
203 getPathList(env_var,Paths);
208 if (tmpPath.set(LLVM_LIBDIR))
209 if (tmpPath.canRead())
210 Paths.push_back(tmpPath);
213 GetSystemLibraryPaths(Paths);
217 Path::GetLLVMDefaultConfigDir() {
218 return Path("/etc/llvm/");
222 Path::GetUserHomeDirectory() {
223 const char* home = getenv("HOME");
226 if (result.set(home))
229 return GetRootDirectory();
233 Path::isFile() const {
237 if (0 != stat(path.c_str(), &buf)) {
238 ThrowErrno(path + ": can't determine type of path object: ");
240 return S_ISREG(buf.st_mode);
244 Path::isDirectory() const {
248 if (0 != stat(path.c_str(), &buf)) {
249 ThrowErrno(path + ": can't determine type of path object: ");
251 return S_ISDIR(buf.st_mode);
255 Path::isHidden() const {
258 size_t slash = path.rfind('/');
259 return (slash != std::string::npos &&
260 slash < path.length()-1 &&
261 path[slash+1] == '.') ||
262 (!path.empty() && slash == std::string::npos && path[0] == '.');
266 Path::getBasename() const {
267 // Find the last slash
268 size_t slash = path.rfind('/');
269 if (slash == std::string::npos)
274 size_t dot = path.rfind('.');
275 if (dot == std::string::npos || dot < slash)
276 return path.substr(slash);
278 return path.substr(slash, dot - slash);
281 bool Path::hasMagicNumber(const std::string &Magic) const {
284 size_t len = Magic.size();
285 assert(len < 1024 && "Request for magic string too long");
286 char* buf = (char*) alloca(1 + len);
287 int fd = ::open(path.c_str(),O_RDONLY);
290 size_t read_len = ::read(fd, buf, len);
298 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
301 assert(len < 1024 && "Request for magic string too long");
302 char* buf = (char*) alloca(1 + len);
303 int fd = ::open(path.c_str(),O_RDONLY);
306 ssize_t bytes_read = ::read(fd, buf, len);
308 if (ssize_t(len) != bytes_read) {
312 Magic.assign(buf,len);
317 Path::isBytecodeFile() const {
322 int fd = ::open(path.c_str(),O_RDONLY);
325 ssize_t bytes_read = ::read(fd, buffer, 4);
330 return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
331 (buffer[3] == 'c' || buffer[3] == 'm'));
335 Path::exists() const {
336 return 0 == access(path.c_str(), F_OK );
340 Path::canRead() const {
341 return 0 == access(path.c_str(), F_OK | R_OK );
345 Path::canWrite() const {
346 return 0 == access(path.c_str(), F_OK | W_OK );
350 Path::canExecute() const {
351 if (0 != access(path.c_str(), R_OK | X_OK ))
354 int r = stat(path.c_str(), &st);
355 if (r != 0 || !S_ISREG(st.st_mode))
361 Path::getLast() const {
362 // Find the last slash
363 size_t pos = path.rfind('/');
365 // Handle the corner cases
366 if (pos == std::string::npos)
369 // If the last character is a slash
370 if (pos == path.length()-1) {
371 // Find the second to last slash
372 size_t pos2 = path.rfind('/', pos-1);
373 if (pos2 == std::string::npos)
374 return path.substr(0,pos);
376 return path.substr(pos2+1,pos-pos2-1);
378 // Return everything after the last slash
379 return path.substr(pos+1);
383 Path::getStatusInfo(StatusInfo& info) const {
385 if (0 != stat(path.c_str(), &buf)) {
386 ThrowErrno(path + ": can't determine type of path object: ");
388 info.fileSize = buf.st_size;
389 info.modTime.fromEpochTime(buf.st_mtime);
390 info.mode = buf.st_mode;
391 info.user = buf.st_uid;
392 info.group = buf.st_gid;
393 info.isDir = S_ISDIR(buf.st_mode);
396 static bool AddPermissionBits(const std::string& Filename, int bits) {
397 // Get the umask value from the operating system. We want to use it
398 // when changing the file's permissions. Since calling umask() sets
399 // the umask and returns its old value, we must call it a second
400 // time to reset it to the user's preference.
401 int mask = umask(0777); // The arg. to umask is arbitrary.
402 umask(mask); // Restore the umask.
404 // Get the file's current mode.
406 if ((stat(Filename.c_str(), &st)) == -1)
409 // Change the file to have whichever permissions bits from 'bits'
410 // that the umask would not disable.
411 if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)
417 void Path::makeReadableOnDisk() {
418 if (!AddPermissionBits(path,0444))
419 ThrowErrno(path + ": can't make file readable");
422 void Path::makeWriteableOnDisk() {
423 if (!AddPermissionBits(path,0222))
424 ThrowErrno(path + ": can't make file writable");
427 void Path::makeExecutableOnDisk() {
428 if (!AddPermissionBits(path,0111))
429 ThrowErrno(path + ": can't make file executable");
433 Path::getDirectoryContents(std::set<Path>& result) const {
436 DIR* direntries = ::opendir(path.c_str());
438 ThrowErrno(path + ": can't open directory");
441 struct dirent* de = ::readdir(direntries);
442 for ( ; de != 0; de = ::readdir(direntries)) {
443 if (de->d_name[0] != '.') {
444 Path aPath(path + (const char*)de->d_name);
446 if (0 != stat(aPath.path.c_str(), &buf)) {
447 int stat_errno = errno;
449 if (0 == lstat(aPath.path.c_str(), &st) && S_ISLNK(st.st_mode))
450 continue; // dangling symlink -- ignore
451 ThrowErrno(aPath.path +
452 ": can't determine file object type", stat_errno);
454 result.insert(aPath);
458 closedir(direntries);
463 Path::set(const std::string& a_path) {
466 std::string save(path);
476 Path::appendComponent(const std::string& name) {
479 std::string save(path);
481 size_t last = path.size() - 1;
482 if (path[last] != '/')
494 Path::eraseComponent() {
495 size_t slashpos = path.rfind('/',path.size());
496 if (slashpos == 0 || slashpos == std::string::npos) {
500 if (slashpos == path.size() - 1)
501 slashpos = path.rfind('/',slashpos-1);
502 if (slashpos == std::string::npos) {
506 path.erase(slashpos);
511 Path::appendSuffix(const std::string& suffix) {
512 std::string save(path);
523 Path::eraseSuffix() {
524 std::string save = path;
525 size_t dotpos = path.rfind('.',path.size());
526 size_t slashpos = path.rfind('/',path.size());
527 if (dotpos != std::string::npos) {
528 if (slashpos == std::string::npos || dotpos > slashpos+1) {
529 path.erase(dotpos, path.size()-dotpos);
539 Path::createDirectoryOnDisk( bool create_parents) {
540 // Get a writeable copy of the path name
541 char pathname[MAXPATHLEN];
542 path.copy(pathname,MAXPATHLEN);
544 // Null-terminate the last component
545 int lastchar = path.length() - 1 ;
546 if (pathname[lastchar] == '/')
547 pathname[lastchar] = 0;
549 pathname[lastchar+1] = 0;
551 // If we're supposed to create intermediate directories
552 if ( create_parents ) {
553 // Find the end of the initial name component
554 char * next = strchr(pathname,'/');
555 if ( pathname[0] == '/')
556 next = strchr(&pathname[1],'/');
558 // Loop through the directory components until we're done
559 while ( next != 0 ) {
561 if (0 != access(pathname, F_OK | R_OK | W_OK))
562 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
563 ThrowErrno(std::string(pathname) + ": can't create directory");
565 next = strchr(next+1,'/');
570 if (0 != access(pathname, F_OK | R_OK))
571 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
572 ThrowErrno(std::string(pathname) + ": can't create directory");
577 Path::createFileOnDisk() {
579 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
581 ThrowErrno(path + ": can't create file");
588 Path::createTemporaryFileOnDisk(bool reuse_current) {
589 // Make this into a unique file name
590 makeUnique( reuse_current );
593 int outFile = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
602 Path::eraseFromDisk(bool remove_contents) const {
603 // Make sure we're dealing with a directory
605 if (0 != unlink(path.c_str()))
606 ThrowErrno(path + ": can't destroy file");
607 } else if (isDirectory()) {
608 if (remove_contents) {
609 // Recursively descend the directory to remove its content
610 std::string cmd("/bin/rm -rf ");
614 // Otherwise, try to just remove the one directory
615 char pathname[MAXPATHLEN];
616 path.copy(pathname,MAXPATHLEN);
617 int lastchar = path.length() - 1 ;
618 if (pathname[lastchar] == '/')
619 pathname[lastchar] = 0;
621 pathname[lastchar+1] = 0;
622 if ( 0 != rmdir(pathname))
623 ThrowErrno(std::string(pathname) + ": can't destroy directory");
632 Path::renamePathOnDisk(const Path& newName) {
633 if (0 != ::rename(path.c_str(), newName.c_str()))
634 ThrowErrno(std::string("can't rename '") + path + "' as '" +
635 newName.toString() + "' ");
640 Path::setStatusInfoOnDisk(const StatusInfo& si) const {
642 utb.actime = si.modTime.toPosixTime();
643 utb.modtime = utb.actime;
644 if (0 != ::utime(path.c_str(),&utb))
645 ThrowErrno(path + ": can't set file modification time");
646 if (0 != ::chmod(path.c_str(),si.mode))
647 ThrowErrno(path + ": can't set mode");
652 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src) {
656 inFile = ::open(Src.c_str(), O_RDONLY);
658 ThrowErrno(Src.toString() + ": can't open source file to copy: ");
660 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
662 ThrowErrno(Dest.toString() +": can't create destination file for copy: ");
664 char Buffer[16*1024];
665 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
667 if (errno != EINTR && errno != EAGAIN)
668 ThrowErrno(Src.toString()+": can't read source file: ");
670 char *BufPtr = Buffer;
672 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
673 if (AmtWritten == -1) {
674 if (errno != EINTR && errno != EAGAIN)
675 ThrowErrno(Dest.toString() + ": can't write destination file: ");
678 BufPtr += AmtWritten;
695 Path::makeUnique(bool reuse_current) {
696 if (reuse_current && !exists())
697 return; // File doesn't exist already, just use it!
699 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
700 // mktemp or our own implementation.
701 char *FNBuffer = (char*) alloca(path.size()+8);
702 path.copy(FNBuffer,path.size());
703 strcpy(FNBuffer+path.size(), "-XXXXXX");
705 #if defined(HAVE_MKSTEMP)
707 if ((TempFD = mkstemp(FNBuffer)) == -1) {
708 ThrowErrno(path + ": can't make unique filename");
711 // We don't need to hold the temp file descriptor... we will trust that no one
712 // will overwrite/delete the file before we can open it again.
717 #elif defined(HAVE_MKTEMP)
718 // If we don't have mkstemp, use the old and obsolete mktemp function.
719 if (mktemp(FNBuffer) == 0) {
720 ThrowErrno(path + ": can't make unique filename");
726 // Okay, looks like we have to do it all by our lonesome.
727 static unsigned FCounter = 0;
728 unsigned offset = path.size() + 1;
729 while ( FCounter < 999999 && exists()) {
730 sprintf(FNBuffer+offset,"%06u",++FCounter);
733 if (FCounter > 999999)
734 throw std::string(path + ": can't make unique filename: too many files");