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.
57 inline bool lastIsSlash(const std::string& path) {
58 return !path.empty() && path[path.length() - 1] == '/';
67 Path::isValid() const {
68 // Check some obvious things
71 else if (path.length() >= MAXPATHLEN)
74 // Check that the characters are ascii chars
75 size_t len = path.length();
77 while (i < len && isascii(path[i]))
83 Path::GetRootDirectory() {
90 Path::GetTemporaryDirectory(std::string* ErrMsg ) {
91 #if defined(HAVE_MKDTEMP)
92 // The best way is with mkdtemp but that's not available on many systems,
93 // Linux and FreeBSD have it. Others probably won't.
94 char pathname[MAXPATHLEN];
95 strcpy(pathname,"/tmp/llvm_XXXXXX");
96 if (0 == mkdtemp(pathname)) {
98 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))) {
116 std::string(pathname) + ": can't create temporary directory");
120 ::unlink(pathname); // start race condition, ignore errors
121 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
123 std::string(pathname) + ": can't create temporary directory");
127 result.set(pathname);
128 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
130 #elif defined(HAVE_MKTEMP)
131 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
132 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
133 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
134 // the XXXXXX with the pid of the process and a letter. That leads to only
135 // twenty six temporary files that can be generated.
136 char pathname[MAXPATHLEN];
137 strcpy(pathname, "/tmp/llvm_XXXXXX");
138 char *TmpName = ::mktemp(pathname);
141 std::string(TmpName) + ": can't create unique directory name");
144 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
146 std::string(TmpName) + ": can't create temporary directory");
151 assert(result.isValid() && "mktemp didn't create a valid pathname!");
154 // This is the worst case implementation. tempnam(3) leaks memory unless its
155 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
156 // issues. The mktemp(3) function doesn't have enough variability in the
157 // temporary name generated. So, we provide our own implementation that
158 // increments an integer from a random number seeded by the current time. This
159 // should be sufficiently unique that we don't have many collisions between
160 // processes. Generally LLVM processes don't run very long and don't use very
161 // many temporary files so this shouldn't be a big issue for LLVM.
162 static time_t num = ::time(0);
163 char pathname[MAXPATHLEN];
166 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
167 } while ( 0 == access(pathname, F_OK ) );
168 if (-1 == ::mkdir(pathname, S_IRWXU)) {
170 std::string(pathname) + ": can't create temporary directory");
174 result.set(pathname);
175 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
180 static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
181 const char* at = path;
182 const char* delim = strchr(at, ':');
184 while( delim != 0 ) {
185 std::string tmp(at, size_t(delim-at));
186 if (tmpPath.set(tmp))
187 if (tmpPath.canRead())
188 Paths.push_back(tmpPath);
190 delim = strchr(at, ':');
193 if (tmpPath.set(std::string(at)))
194 if (tmpPath.canRead())
195 Paths.push_back(tmpPath);
200 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
201 #ifdef LTDL_SHLIBPATH_VAR
202 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
204 getPathList(env_var,Paths);
207 // FIXME: Should this look at LD_LIBRARY_PATH too?
208 Paths.push_back(sys::Path("/usr/local/lib/"));
209 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
210 Paths.push_back(sys::Path("/usr/lib/"));
211 Paths.push_back(sys::Path("/lib/"));
215 Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
216 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
218 getPathList(env_var,Paths);
223 if (tmpPath.set(LLVM_LIBDIR))
224 if (tmpPath.canRead())
225 Paths.push_back(tmpPath);
228 GetSystemLibraryPaths(Paths);
232 Path::GetLLVMDefaultConfigDir() {
233 return Path("/etc/llvm/");
237 Path::GetUserHomeDirectory() {
238 const char* home = getenv("HOME");
241 if (result.set(home))
244 return GetRootDirectory();
249 Path::getBasename() const {
250 // Find the last slash
251 size_t slash = path.rfind('/');
252 if (slash == std::string::npos)
257 size_t dot = path.rfind('.');
258 if (dot == std::string::npos || dot < slash)
259 return path.substr(slash);
261 return path.substr(slash, dot - slash);
264 bool Path::hasMagicNumber(const std::string &Magic) const {
265 size_t len = Magic.size();
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 size_t read_len = ::read(fd, buf, len);
279 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
280 assert(len < 1024 && "Request for magic string too long");
281 char* buf = (char*) alloca(1 + len);
282 int fd = ::open(path.c_str(), O_RDONLY);
285 ssize_t bytes_read = ::read(fd, buf, len);
287 if (ssize_t(len) != bytes_read) {
291 Magic.assign(buf,len);
296 Path::isBytecodeFile() const {
299 int fd = ::open(path.c_str(), O_RDONLY);
302 ssize_t bytes_read = ::read(fd, buffer, 4);
307 return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
308 (buffer[3] == 'c' || buffer[3] == 'm'));
312 Path::exists() const {
313 return 0 == access(path.c_str(), F_OK );
317 Path::canRead() const {
318 return 0 == access(path.c_str(), F_OK | R_OK );
322 Path::canWrite() const {
323 return 0 == access(path.c_str(), F_OK | W_OK );
327 Path::canExecute() const {
328 if (0 != access(path.c_str(), R_OK | X_OK ))
331 int r = stat(path.c_str(), &st);
332 if (r != 0 || !S_ISREG(st.st_mode))
338 Path::getLast() const {
339 // Find the last slash
340 size_t pos = path.rfind('/');
342 // Handle the corner cases
343 if (pos == std::string::npos)
346 // If the last character is a slash
347 if (pos == path.length()-1) {
348 // Find the second to last slash
349 size_t pos2 = path.rfind('/', pos-1);
350 if (pos2 == std::string::npos)
351 return path.substr(0,pos);
353 return path.substr(pos2+1,pos-pos2-1);
355 // Return everything after the last slash
356 return path.substr(pos+1);
360 Path::getFileStatus(FileStatus &info, std::string *ErrStr) const {
362 if (0 != stat(path.c_str(), &buf))
363 return MakeErrMsg(ErrStr,
364 path + ": can't get status of file '" + path + "'");
365 info.fileSize = buf.st_size;
366 info.modTime.fromEpochTime(buf.st_mtime);
367 info.mode = buf.st_mode;
368 info.user = buf.st_uid;
369 info.group = buf.st_gid;
370 info.isDir = S_ISDIR(buf.st_mode);
371 info.isFile = S_ISREG(buf.st_mode);
375 static bool AddPermissionBits(const Path &File, int bits) {
376 // Get the umask value from the operating system. We want to use it
377 // when changing the file's permissions. Since calling umask() sets
378 // the umask and returns its old value, we must call it a second
379 // time to reset it to the user's preference.
380 int mask = umask(0777); // The arg. to umask is arbitrary.
381 umask(mask); // Restore the umask.
383 // Get the file's current mode.
385 if (File.getFileStatus(Stat)) return false;
387 // Change the file to have whichever permissions bits from 'bits'
388 // that the umask would not disable.
389 if ((chmod(File.c_str(), (Stat.getMode() | (bits & ~mask)))) == -1)
395 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
396 if (!AddPermissionBits(*this, 0444))
397 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
401 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
402 if (!AddPermissionBits(*this, 0222))
403 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
407 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
408 if (!AddPermissionBits(*this, 0111))
409 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
414 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
415 DIR* direntries = ::opendir(path.c_str());
417 return MakeErrMsg(ErrMsg, path + ": can't open directory");
419 std::string dirPath = path;
420 if (!lastIsSlash(dirPath))
424 struct dirent* de = ::readdir(direntries);
425 for ( ; de != 0; de = ::readdir(direntries)) {
426 if (de->d_name[0] != '.') {
427 Path aPath(dirPath + (const char*)de->d_name);
429 if (0 != lstat(aPath.path.c_str(), &st)) {
430 if (S_ISLNK(st.st_mode))
431 continue; // dangling symlink -- ignore
432 return MakeErrMsg(ErrMsg,
433 aPath.path + ": can't determine file object type");
435 result.insert(aPath);
439 closedir(direntries);
444 Path::set(const std::string& a_path) {
447 std::string save(path);
457 Path::appendComponent(const std::string& name) {
460 std::string save(path);
461 if (!lastIsSlash(path))
472 Path::eraseComponent() {
473 size_t slashpos = path.rfind('/',path.size());
474 if (slashpos == 0 || slashpos == std::string::npos) {
478 if (slashpos == path.size() - 1)
479 slashpos = path.rfind('/',slashpos-1);
480 if (slashpos == std::string::npos) {
484 path.erase(slashpos);
489 Path::appendSuffix(const std::string& suffix) {
490 std::string save(path);
501 Path::eraseSuffix() {
502 std::string save = path;
503 size_t dotpos = path.rfind('.',path.size());
504 size_t slashpos = path.rfind('/',path.size());
505 if (dotpos != std::string::npos) {
506 if (slashpos == std::string::npos || dotpos > slashpos+1) {
507 path.erase(dotpos, path.size()-dotpos);
517 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
518 // Get a writeable copy of the path name
519 char pathname[MAXPATHLEN];
520 path.copy(pathname,MAXPATHLEN);
522 // Null-terminate the last component
523 int lastchar = path.length() - 1 ;
524 if (pathname[lastchar] == '/')
525 pathname[lastchar] = 0;
527 pathname[lastchar+1] = 0;
529 // If we're supposed to create intermediate directories
530 if ( create_parents ) {
531 // Find the end of the initial name component
532 char * next = strchr(pathname,'/');
533 if ( pathname[0] == '/')
534 next = strchr(&pathname[1],'/');
536 // Loop through the directory components until we're done
537 while ( next != 0 ) {
539 if (0 != access(pathname, F_OK | R_OK | W_OK))
540 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
541 return MakeErrMsg(ErrMsg,
542 std::string(pathname) + ": can't create directory");
545 next = strchr(next+1,'/');
550 if (0 != access(pathname, F_OK | R_OK))
551 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
552 return MakeErrMsg(ErrMsg,
553 std::string(pathname) + ": can't create directory");
559 Path::createFileOnDisk(std::string* ErrMsg) {
561 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
563 return MakeErrMsg(ErrMsg, path + ": can't create file");
569 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
570 // Make this into a unique file name
571 if (makeUnique( reuse_current, ErrMsg ))
575 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
577 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
583 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
585 if (getFileStatus(Status, ErrStr))
588 // Note: this check catches strange situations. In all cases, LLVM should only
589 // be involved in the creation and deletion of regular files. This check
590 // ensures that what we're trying to erase is a regular file. It effectively
591 // prevents LLVM from erasing things like /dev/null, any block special file,
592 // or other things that aren't "regular" files.
594 if (unlink(path.c_str()) != 0)
595 return MakeErrMsg(ErrStr, path + ": can't destroy file");
600 if (ErrStr) *ErrStr = "not a file or directory";
603 if (remove_contents) {
604 // Recursively descend the directory to remove its contents.
605 std::string cmd = "/bin/rm -rf " + path;
610 // Otherwise, try to just remove the one directory.
611 char pathname[MAXPATHLEN];
612 path.copy(pathname, MAXPATHLEN);
613 int lastchar = path.length() - 1 ;
614 if (pathname[lastchar] == '/')
615 pathname[lastchar] = 0;
617 pathname[lastchar+1] = 0;
619 if (rmdir(pathname) != 0)
620 return MakeErrMsg(ErrStr,
621 std::string(pathname) + ": can't destroy directory");
626 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
627 if (0 != ::rename(path.c_str(), newName.c_str()))
628 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
629 newName.toString() + "' ");
634 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
636 utb.actime = si.modTime.toPosixTime();
637 utb.modtime = utb.actime;
638 if (0 != ::utime(path.c_str(),&utb))
639 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
640 if (0 != ::chmod(path.c_str(),si.mode))
641 return MakeErrMsg(ErrStr, path + ": can't set mode");
646 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
649 inFile = ::open(Src.c_str(), O_RDONLY);
651 return MakeErrMsg(ErrMsg, Src.toString() +
652 ": can't open source file to copy");
654 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
657 return MakeErrMsg(ErrMsg, Dest.toString() +
658 ": can't create destination file for copy");
661 char Buffer[16*1024];
662 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
664 if (errno != EINTR && errno != EAGAIN) {
667 return MakeErrMsg(ErrMsg, 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) {
677 return MakeErrMsg(ErrMsg, Dest.toString() +
678 ": can't write destination file: ");
682 BufPtr += AmtWritten;
693 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
694 if (reuse_current && !exists())
695 return false; // File doesn't exist already, just use it!
697 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
698 // mktemp or our own implementation.
699 char *FNBuffer = (char*) alloca(path.size()+8);
700 path.copy(FNBuffer,path.size());
701 strcpy(FNBuffer+path.size(), "-XXXXXX");
703 #if defined(HAVE_MKSTEMP)
705 if ((TempFD = mkstemp(FNBuffer)) == -1)
706 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
708 // We don't need to hold the temp file descriptor... we will trust that no one
709 // will overwrite/delete the file before we can open it again.
714 #elif defined(HAVE_MKTEMP)
715 // If we don't have mkstemp, use the old and obsolete mktemp function.
716 if (mktemp(FNBuffer) == 0)
717 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
722 // Okay, looks like we have to do it all by our lonesome.
723 static unsigned FCounter = 0;
724 unsigned offset = path.size() + 1;
725 while ( FCounter < 999999 && exists()) {
726 sprintf(FNBuffer+offset,"%06u",++FCounter);
729 if (FCounter > 999999)
730 return MakeErrMsg(ErrMsg,
731 path + ": can't make unique filename: too many files");
736 } // end llvm namespace