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/config.h>
20 #include <llvm/Config/alloca.h>
30 Path::Path(const std::string& unverified_path)
31 : path(unverified_path)
33 if (unverified_path.empty())
39 ThrowErrno(unverified_path + ": path is not valid");
43 Path::GetRootDirectory() {
45 result.setDirectory("/");
49 static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
50 const char* at = path;
51 const char* delim = strchr(at, ':');
54 std::string tmp(at, size_t(delim-at));
55 if (tmpPath.setDirectory(tmp))
56 if (tmpPath.readable())
57 Paths.push_back(tmpPath);
59 delim = strchr(at, ':');
62 if (tmpPath.setDirectory(std::string(at)))
63 if (tmpPath.readable())
64 Paths.push_back(tmpPath);
68 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
69 #ifdef LTDL_SHLIBPATH_VAR
70 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
72 getPathList(env_var,Paths);
75 // FIXME: Should this look at LD_LIBRARY_PATH too?
76 Paths.push_back(sys::Path("/usr/local/lib/"));
77 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
78 Paths.push_back(sys::Path("/usr/lib/"));
79 Paths.push_back(sys::Path("/lib/"));
83 Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
84 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
86 getPathList(env_var,Paths);
90 Path tmpPath(std::string(LLVMGCCDIR) + "lib/");
91 if (tmpPath.readable())
92 Paths.push_back(tmpPath);
98 if (tmpPath.setDirectory(LLVM_LIBDIR))
99 if (tmpPath.readable())
100 Paths.push_back(tmpPath);
103 GetSystemLibraryPaths(Paths);
107 Path::GetLLVMDefaultConfigDir() {
108 return Path("/etc/llvm/");
112 Path::GetUserHomeDirectory() {
113 const char* home = getenv("HOME");
116 if (result.setDirectory(home))
119 return GetRootDirectory();
123 Path::isFile() const {
124 return (isValid() && path[path.length()-1] != '/');
128 Path::isDirectory() const {
129 return (isValid() && path[path.length()-1] == '/');
133 Path::getBasename() const {
134 // Find the last slash
135 size_t slash = path.rfind('/');
136 if (slash == std::string::npos)
141 return path.substr(slash, path.rfind('.'));
144 bool Path::hasMagicNumber(const std::string &Magic) const {
145 size_t len = Magic.size();
146 assert(len < 1024 && "Request for magic string too long");
147 char* buf = (char*) alloca(1 + len);
148 int fd = ::open(path.c_str(),O_RDONLY);
151 size_t read_len = ::read(fd, buf, len);
159 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
162 assert(len < 1024 && "Request for magic string too long");
163 char* buf = (char*) alloca(1 + len);
164 int fd = ::open(path.c_str(),O_RDONLY);
167 ssize_t bytes_read = ::read(fd, buf, len);
169 if (ssize_t(len) != bytes_read) {
173 Magic.assign(buf,len);
178 Path::isBytecodeFile() const {
181 int fd = ::open(path.c_str(),O_RDONLY);
184 ssize_t bytes_read = ::read(fd, buffer, 4);
189 return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
190 (buffer[3] == 'c' || buffer[3] == 'm'));
194 Path::exists() const {
195 return 0 == access(path.c_str(), F_OK );
199 Path::readable() const {
200 return 0 == access(path.c_str(), F_OK | R_OK );
204 Path::writable() const {
205 return 0 == access(path.c_str(), F_OK | W_OK );
209 Path::executable() const {
210 return 0 == access(path.c_str(), R_OK | X_OK );
214 Path::getLast() const {
215 // Find the last slash
216 size_t pos = path.rfind('/');
218 // Handle the corner cases
219 if (pos == std::string::npos)
222 // If the last character is a slash
223 if (pos == path.length()-1) {
224 // Find the second to last slash
225 size_t pos2 = path.rfind('/', pos-1);
226 if (pos2 == std::string::npos)
227 return path.substr(0,pos);
229 return path.substr(pos2+1,pos-pos2-1);
231 // Return everything after the last slash
232 return path.substr(pos+1);
236 Path::getStatusInfo(StatusInfo& info) const {
238 if (0 != stat(path.c_str(), &buf)) {
239 ThrowErrno(std::string("Can't get status: ")+path);
241 info.fileSize = buf.st_size;
242 info.modTime.fromEpochTime(buf.st_mtime);
243 info.mode = buf.st_mode;
244 info.user = buf.st_uid;
245 info.group = buf.st_gid;
246 info.isDir = S_ISDIR(buf.st_mode);
247 if (info.isDir && path[path.length()-1] != '/')
251 static bool AddPermissionBits(const std::string& Filename, int bits) {
252 // Get the umask value from the operating system. We want to use it
253 // when changing the file's permissions. Since calling umask() sets
254 // the umask and returns its old value, we must call it a second
255 // time to reset it to the user's preference.
256 int mask = umask(0777); // The arg. to umask is arbitrary.
257 umask(mask); // Restore the umask.
259 // Get the file's current mode.
261 if ((stat(Filename.c_str(), &st)) == -1)
264 // Change the file to have whichever permissions bits from 'bits'
265 // that the umask would not disable.
266 if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)
272 void Path::makeReadable() {
273 if (!AddPermissionBits(path,0444))
274 ThrowErrno(path + ": can't make file readable");
277 void Path::makeWriteable() {
278 if (!AddPermissionBits(path,0222))
279 ThrowErrno(path + ": can't make file writable");
282 void Path::makeExecutable() {
283 if (!AddPermissionBits(path,0111))
284 ThrowErrno(path + ": can't make file executable");
288 Path::getDirectoryContents(std::set<Path>& result) const {
291 DIR* direntries = ::opendir(path.c_str());
293 ThrowErrno(path + ": can't open directory");
296 struct dirent* de = ::readdir(direntries);
298 if (de->d_name[0] != '.') {
299 Path aPath(path + (const char*)de->d_name);
301 if (0 != stat(aPath.path.c_str(), &buf))
302 ThrowErrno(aPath.path + ": can't get status");
303 if (S_ISDIR(buf.st_mode))
305 result.insert(aPath);
307 de = ::readdir(direntries);
310 closedir(direntries);
315 Path::setDirectory(const std::string& a_path) {
316 if (a_path.size() == 0)
320 size_t last = a_path.size() -1;
321 if (a_path[last] != '/')
331 Path::setFile(const std::string& a_path) {
332 if (a_path.size() == 0)
336 size_t last = a_path.size() - 1;
337 while (last > 0 && a_path[last] == '/')
348 Path::appendDirectory(const std::string& dir) {
362 Path::elideDirectory() {
365 size_t slashpos = path.rfind('/',path.size());
366 if (slashpos == 0 || slashpos == std::string::npos)
368 if (slashpos == path.size() - 1)
369 slashpos = path.rfind('/',slashpos-1);
370 if (slashpos == std::string::npos)
372 path.erase(slashpos);
377 Path::appendFile(const std::string& file) {
393 size_t slashpos = path.rfind('/',path.size());
394 if (slashpos == std::string::npos)
396 path.erase(slashpos+1);
401 Path::appendSuffix(const std::string& suffix) {
415 Path::elideSuffix() {
416 if (isDirectory()) return false;
417 size_t dotpos = path.rfind('.',path.size());
418 size_t slashpos = path.rfind('/',path.size());
419 if (slashpos != std::string::npos && dotpos != std::string::npos &&
421 path.erase(dotpos, path.size()-dotpos);
429 Path::createDirectory( bool create_parents) {
430 // Make sure we're dealing with a directory
431 if (!isDirectory()) return false;
433 // Get a writeable copy of the path name
434 char pathname[MAXPATHLEN];
435 path.copy(pathname,MAXPATHLEN);
437 // Null-terminate the last component
438 int lastchar = path.length() - 1 ;
439 if (pathname[lastchar] == '/')
440 pathname[lastchar] = 0;
442 pathname[lastchar+1] = 0;
444 // If we're supposed to create intermediate directories
445 if ( create_parents ) {
446 // Find the end of the initial name component
447 char * next = strchr(pathname,'/');
448 if ( pathname[0] == '/')
449 next = strchr(&pathname[1],'/');
451 // Loop through the directory components until we're done
452 while ( next != 0 ) {
454 if (0 != access(pathname, F_OK | R_OK | W_OK))
455 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
456 ThrowErrno(std::string(pathname) + ": Can't create directory");
458 next = strchr(next+1,'/');
463 if (0 != access(pathname, F_OK | R_OK))
464 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
465 ThrowErrno(std::string(pathname) + ": Can't create directory");
471 // Make sure we're dealing with a file
472 if (!isFile()) return false;
475 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
477 ThrowErrno(path + ": Can't create file");
484 Path::createTemporaryFile() {
485 // Make sure we're dealing with a file
489 // Make this into a unique file name
493 int outFile = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
502 Path::destroyDirectory(bool remove_contents) {
503 // Make sure we're dealing with a directory
504 if (!isDirectory()) return false;
506 // If it doesn't exist, we're done.
507 if (!exists()) return true;
509 if (remove_contents) {
510 // Recursively descend the directory to remove its content
511 std::string cmd("/bin/rm -rf ");
515 // Otherwise, try to just remove the one directory
516 char pathname[MAXPATHLEN];
517 path.copy(pathname,MAXPATHLEN);
518 int lastchar = path.length() - 1 ;
519 if (pathname[lastchar] == '/')
520 pathname[lastchar] = 0;
522 pathname[lastchar+1] = 0;
523 if ( 0 != rmdir(pathname))
524 ThrowErrno(std::string(pathname) + ": Can't destroy directory");
530 Path::destroyFile() {
531 if (!isFile()) return false;
532 if (0 != unlink(path.c_str()))
533 ThrowErrno(path + ": Can't destroy file");
538 Path::renameFile(const Path& newName) {
539 if (!isFile()) return false;
540 if (0 != rename(path.c_str(), newName.c_str()))
541 ThrowErrno(std::string("can't rename ") + path + " as " +
547 Path::setStatusInfo(const StatusInfo& si) const {
548 if (!isFile()) return false;
550 utb.actime = si.modTime.toPosixTime();
551 utb.modtime = utb.actime;
552 if (0 != ::utime(path.c_str(),&utb))
553 ThrowErrno(path + ": can't set file modification time");
554 if (0 != ::chmod(path.c_str(),si.mode))
555 ThrowErrno(path + ": can't set mode");
560 CopyFile(const sys::Path &Dest, const sys::Path &Src) {
564 inFile = ::open(Src.c_str(), O_RDONLY);
566 ThrowErrno("Cannnot open source file to copy: " + Src.toString());
568 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
570 ThrowErrno("Cannnot create destination file for copy: " +Dest.toString());
572 char Buffer[16*1024];
573 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
575 if (errno != EINTR && errno != EAGAIN)
576 ThrowErrno("Can't read source file: " + Src.toString());
578 char *BufPtr = Buffer;
580 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
581 if (AmtWritten == -1) {
582 if (errno != EINTR && errno != EAGAIN)
583 ThrowErrno("Can't write destination file: " + Dest.toString());
586 BufPtr += AmtWritten;
605 return; // File doesn't exist already, just use it!
607 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
608 // mktemp or our own implementation.
609 char *FNBuffer = (char*) alloca(path.size()+8);
610 path.copy(FNBuffer,path.size());
611 strcpy(FNBuffer+path.size(), "-XXXXXX");
613 #if defined(HAVE_MKSTEMP)
615 if ((TempFD = mkstemp(FNBuffer)) == -1) {
616 ThrowErrno("Cannot make unique filename for '" + path + "'");
619 // We don't need to hold the temp file descriptor... we will trust that no one
620 // will overwrite/delete the file before we can open it again.
625 #elif defined(HAVE_MKTEMP)
626 // If we don't have mkstemp, use the old and obsolete mktemp function.
627 if (mktemp(FNBuffer) == 0) {
628 ThrowErrno("Cannot make unique filename for '" + path + "'");
634 // Okay, looks like we have to do it all by our lonesome.
635 static unsigned FCounter = 0;
636 unsigned offset = path.size() + 1;
637 while ( FCounter < 999999 && exists()) {
638 sprintf(FNBuffer+offset,"%06u",++FCounter);
641 if (FCounter > 999999)
642 throw std::string("Cannot make unique filename for '" + path + "'");