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"
29 Path::Path(const std::string& unverified_path) : path(unverified_path) {
30 if (unverified_path.empty())
36 ThrowErrno(unverified_path + ": path is not valid");
40 Path::GetRootDirectory() {
42 result.setDirectory("/");
46 static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
47 const char* at = path;
48 const char* delim = strchr(at, ':');
51 std::string tmp(at, size_t(delim-at));
52 if (tmpPath.setDirectory(tmp))
53 if (tmpPath.readable())
54 Paths.push_back(tmpPath);
56 delim = strchr(at, ':');
59 if (tmpPath.setDirectory(std::string(at)))
60 if (tmpPath.readable())
61 Paths.push_back(tmpPath);
66 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
67 #ifdef LTDL_SHLIBPATH_VAR
68 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
70 getPathList(env_var,Paths);
73 // FIXME: Should this look at LD_LIBRARY_PATH too?
74 Paths.push_back(sys::Path("/usr/local/lib/"));
75 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
76 Paths.push_back(sys::Path("/usr/lib/"));
77 Paths.push_back(sys::Path("/lib/"));
81 Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
82 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
84 getPathList(env_var,Paths);
89 if (tmpPath.setDirectory(LLVM_LIBDIR))
90 if (tmpPath.readable())
91 Paths.push_back(tmpPath);
94 GetSystemLibraryPaths(Paths);
98 Path::GetLLVMDefaultConfigDir() {
99 return Path("/etc/llvm/");
103 Path::GetUserHomeDirectory() {
104 const char* home = getenv("HOME");
107 if (result.setDirectory(home))
110 return GetRootDirectory();
114 Path::isFile() const {
115 return (isValid() && path[path.length()-1] != '/');
119 Path::isDirectory() const {
120 return (isValid() && path[path.length()-1] == '/');
124 Path::getBasename() const {
125 // Find the last slash
126 size_t slash = path.rfind('/');
127 if (slash == std::string::npos)
132 return path.substr(slash, path.rfind('.'));
135 bool Path::hasMagicNumber(const std::string &Magic) const {
136 size_t len = Magic.size();
137 assert(len < 1024 && "Request for magic string too long");
138 char* buf = (char*) alloca(1 + len);
139 int fd = ::open(path.c_str(),O_RDONLY);
142 size_t read_len = ::read(fd, buf, len);
150 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
153 assert(len < 1024 && "Request for magic string too long");
154 char* buf = (char*) alloca(1 + len);
155 int fd = ::open(path.c_str(),O_RDONLY);
158 ssize_t bytes_read = ::read(fd, buf, len);
160 if (ssize_t(len) != bytes_read) {
164 Magic.assign(buf,len);
169 Path::isBytecodeFile() const {
172 int fd = ::open(path.c_str(),O_RDONLY);
175 ssize_t bytes_read = ::read(fd, buffer, 4);
180 return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
181 (buffer[3] == 'c' || buffer[3] == 'm'));
185 Path::exists() const {
186 return 0 == access(path.c_str(), F_OK );
190 Path::readable() const {
191 return 0 == access(path.c_str(), F_OK | R_OK );
195 Path::writable() const {
196 return 0 == access(path.c_str(), F_OK | W_OK );
200 Path::executable() const {
201 return 0 == access(path.c_str(), R_OK | X_OK );
205 Path::getLast() const {
206 // Find the last slash
207 size_t pos = path.rfind('/');
209 // Handle the corner cases
210 if (pos == std::string::npos)
213 // If the last character is a slash
214 if (pos == path.length()-1) {
215 // Find the second to last slash
216 size_t pos2 = path.rfind('/', pos-1);
217 if (pos2 == std::string::npos)
218 return path.substr(0,pos);
220 return path.substr(pos2+1,pos-pos2-1);
222 // Return everything after the last slash
223 return path.substr(pos+1);
227 Path::getStatusInfo(StatusInfo& info) const {
229 if (0 != stat(path.c_str(), &buf)) {
230 ThrowErrno(std::string("Can't get status: ")+path);
232 info.fileSize = buf.st_size;
233 info.modTime.fromEpochTime(buf.st_mtime);
234 info.mode = buf.st_mode;
235 info.user = buf.st_uid;
236 info.group = buf.st_gid;
237 info.isDir = S_ISDIR(buf.st_mode);
238 if (info.isDir && path[path.length()-1] != '/')
242 static bool AddPermissionBits(const std::string& Filename, int bits) {
243 // Get the umask value from the operating system. We want to use it
244 // when changing the file's permissions. Since calling umask() sets
245 // the umask and returns its old value, we must call it a second
246 // time to reset it to the user's preference.
247 int mask = umask(0777); // The arg. to umask is arbitrary.
248 umask(mask); // Restore the umask.
250 // Get the file's current mode.
252 if ((stat(Filename.c_str(), &st)) == -1)
255 // Change the file to have whichever permissions bits from 'bits'
256 // that the umask would not disable.
257 if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)
263 void Path::makeReadable() {
264 if (!AddPermissionBits(path,0444))
265 ThrowErrno(path + ": can't make file readable");
268 void Path::makeWriteable() {
269 if (!AddPermissionBits(path,0222))
270 ThrowErrno(path + ": can't make file writable");
273 void Path::makeExecutable() {
274 if (!AddPermissionBits(path,0111))
275 ThrowErrno(path + ": can't make file executable");
279 Path::getDirectoryContents(std::set<Path>& result) const {
282 DIR* direntries = ::opendir(path.c_str());
284 ThrowErrno(path + ": can't open directory");
287 struct dirent* de = ::readdir(direntries);
289 if (de->d_name[0] != '.') {
290 Path aPath(path + (const char*)de->d_name);
292 if (0 != stat(aPath.path.c_str(), &buf))
293 ThrowErrno(aPath.path + ": can't get status");
294 if (S_ISDIR(buf.st_mode))
296 result.insert(aPath);
298 de = ::readdir(direntries);
301 closedir(direntries);
306 Path::setDirectory(const std::string& a_path) {
307 if (a_path.size() == 0)
311 size_t last = a_path.size() -1;
312 if (a_path[last] != '/')
322 Path::setFile(const std::string& a_path) {
323 if (a_path.size() == 0)
327 size_t last = a_path.size() - 1;
328 while (last > 0 && a_path[last] == '/')
339 Path::appendDirectory(const std::string& dir) {
353 Path::elideDirectory() {
356 size_t slashpos = path.rfind('/',path.size());
357 if (slashpos == 0 || slashpos == std::string::npos)
359 if (slashpos == path.size() - 1)
360 slashpos = path.rfind('/',slashpos-1);
361 if (slashpos == std::string::npos)
363 path.erase(slashpos);
368 Path::appendFile(const std::string& file) {
384 size_t slashpos = path.rfind('/',path.size());
385 if (slashpos == std::string::npos)
387 path.erase(slashpos+1);
392 Path::appendSuffix(const std::string& suffix) {
406 Path::elideSuffix() {
407 if (isDirectory()) return false;
408 size_t dotpos = path.rfind('.',path.size());
409 size_t slashpos = path.rfind('/',path.size());
410 if (slashpos != std::string::npos && dotpos != std::string::npos &&
412 path.erase(dotpos, path.size()-dotpos);
420 Path::createDirectory( bool create_parents) {
421 // Make sure we're dealing with a directory
422 if (!isDirectory()) return false;
424 // Get a writeable copy of the path name
425 char pathname[MAXPATHLEN];
426 path.copy(pathname,MAXPATHLEN);
428 // Null-terminate the last component
429 int lastchar = path.length() - 1 ;
430 if (pathname[lastchar] == '/')
431 pathname[lastchar] = 0;
433 pathname[lastchar+1] = 0;
435 // If we're supposed to create intermediate directories
436 if ( create_parents ) {
437 // Find the end of the initial name component
438 char * next = strchr(pathname,'/');
439 if ( pathname[0] == '/')
440 next = strchr(&pathname[1],'/');
442 // Loop through the directory components until we're done
443 while ( next != 0 ) {
445 if (0 != access(pathname, F_OK | R_OK | W_OK))
446 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
447 ThrowErrno(std::string(pathname) + ": Can't create directory");
449 next = strchr(next+1,'/');
454 if (0 != access(pathname, F_OK | R_OK))
455 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
456 ThrowErrno(std::string(pathname) + ": Can't create directory");
462 // Make sure we're dealing with a file
463 if (!isFile()) return false;
466 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
468 ThrowErrno(path + ": Can't create file");
475 Path::createTemporaryFile(bool reuse_current) {
476 // Make sure we're dealing with a file
480 // Make this into a unique file name
481 makeUnique( reuse_current );
484 int outFile = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
493 Path::destroyDirectory(bool remove_contents) const {
494 // Make sure we're dealing with a directory
495 if (!isDirectory()) return false;
497 // If it doesn't exist, we're done.
498 if (!exists()) return true;
500 if (remove_contents) {
501 // Recursively descend the directory to remove its content
502 std::string cmd("/bin/rm -rf ");
506 // Otherwise, try to just remove the one directory
507 char pathname[MAXPATHLEN];
508 path.copy(pathname,MAXPATHLEN);
509 int lastchar = path.length() - 1 ;
510 if (pathname[lastchar] == '/')
511 pathname[lastchar] = 0;
513 pathname[lastchar+1] = 0;
514 if ( 0 != rmdir(pathname))
515 ThrowErrno(std::string(pathname) + ": Can't destroy directory");
521 Path::destroyFile() const {
522 if (!isFile()) return false;
523 if (0 != unlink(path.c_str()))
524 ThrowErrno(path + ": Can't destroy file");
529 Path::renameFile(const Path& newName) {
530 if (!isFile()) return false;
531 if (0 != rename(path.c_str(), newName.c_str()))
532 ThrowErrno(std::string("can't rename ") + path + " as " +
538 Path::setStatusInfo(const StatusInfo& si) const {
539 if (!isFile()) return false;
541 utb.actime = si.modTime.toPosixTime();
542 utb.modtime = utb.actime;
543 if (0 != ::utime(path.c_str(),&utb))
544 ThrowErrno(path + ": can't set file modification time");
545 if (0 != ::chmod(path.c_str(),si.mode))
546 ThrowErrno(path + ": can't set mode");
551 CopyFile(const sys::Path &Dest, const sys::Path &Src) {
555 inFile = ::open(Src.c_str(), O_RDONLY);
557 ThrowErrno("Cannnot open source file to copy: " + Src.toString());
559 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
561 ThrowErrno("Cannnot create destination file for copy: " +Dest.toString());
563 char Buffer[16*1024];
564 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
566 if (errno != EINTR && errno != EAGAIN)
567 ThrowErrno("Can't read source file: " + Src.toString());
569 char *BufPtr = Buffer;
571 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
572 if (AmtWritten == -1) {
573 if (errno != EINTR && errno != EAGAIN)
574 ThrowErrno("Can't write destination file: " + Dest.toString());
577 BufPtr += AmtWritten;
594 Path::makeUnique(bool reuse_current) {
595 if (reuse_current && !exists())
596 return; // File doesn't exist already, just use it!
598 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
599 // mktemp or our own implementation.
600 char *FNBuffer = (char*) alloca(path.size()+8);
601 path.copy(FNBuffer,path.size());
602 strcpy(FNBuffer+path.size(), "-XXXXXX");
604 #if defined(HAVE_MKSTEMP)
606 if ((TempFD = mkstemp(FNBuffer)) == -1) {
607 ThrowErrno("Cannot make unique filename for '" + path + "'");
610 // We don't need to hold the temp file descriptor... we will trust that no one
611 // will overwrite/delete the file before we can open it again.
616 #elif defined(HAVE_MKTEMP)
617 // If we don't have mkstemp, use the old and obsolete mktemp function.
618 if (mktemp(FNBuffer) == 0) {
619 ThrowErrno("Cannot make unique filename for '" + path + "'");
625 // Okay, looks like we have to do it all by our lonesome.
626 static unsigned FCounter = 0;
627 unsigned offset = path.size() + 1;
628 while ( FCounter < 999999 && exists()) {
629 sprintf(FNBuffer+offset,"%06u",++FCounter);
632 if (FCounter > 999999)
633 throw std::string("Cannot make unique filename for '" + path + "'");