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);
91 if (tmpPath.setDirectory(LLVM_LIBDIR))
92 if (tmpPath.readable())
93 Paths.push_back(tmpPath);
96 GetSystemLibraryPaths(Paths);
100 Path::GetLLVMDefaultConfigDir() {
101 return Path("/etc/llvm/");
105 Path::GetUserHomeDirectory() {
106 const char* home = getenv("HOME");
109 if (result.setDirectory(home))
112 return GetRootDirectory();
116 Path::isFile() const {
117 return (isValid() && path[path.length()-1] != '/');
121 Path::isDirectory() const {
122 return (isValid() && path[path.length()-1] == '/');
126 Path::getBasename() const {
127 // Find the last slash
128 size_t slash = path.rfind('/');
129 if (slash == std::string::npos)
134 return path.substr(slash, path.rfind('.'));
137 bool Path::hasMagicNumber(const std::string &Magic) const {
138 size_t len = Magic.size();
139 assert(len < 1024 && "Request for magic string too long");
140 char* buf = (char*) alloca(1 + len);
141 int fd = ::open(path.c_str(),O_RDONLY);
144 size_t read_len = ::read(fd, buf, len);
152 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
155 assert(len < 1024 && "Request for magic string too long");
156 char* buf = (char*) alloca(1 + len);
157 int fd = ::open(path.c_str(),O_RDONLY);
160 ssize_t bytes_read = ::read(fd, buf, len);
162 if (ssize_t(len) != bytes_read) {
166 Magic.assign(buf,len);
171 Path::isBytecodeFile() const {
174 int fd = ::open(path.c_str(),O_RDONLY);
177 ssize_t bytes_read = ::read(fd, buffer, 4);
182 return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
183 (buffer[3] == 'c' || buffer[3] == 'm'));
187 Path::exists() const {
188 return 0 == access(path.c_str(), F_OK );
192 Path::readable() const {
193 return 0 == access(path.c_str(), F_OK | R_OK );
197 Path::writable() const {
198 return 0 == access(path.c_str(), F_OK | W_OK );
202 Path::executable() const {
203 return 0 == access(path.c_str(), R_OK | X_OK );
207 Path::getLast() const {
208 // Find the last slash
209 size_t pos = path.rfind('/');
211 // Handle the corner cases
212 if (pos == std::string::npos)
215 // If the last character is a slash
216 if (pos == path.length()-1) {
217 // Find the second to last slash
218 size_t pos2 = path.rfind('/', pos-1);
219 if (pos2 == std::string::npos)
220 return path.substr(0,pos);
222 return path.substr(pos2+1,pos-pos2-1);
224 // Return everything after the last slash
225 return path.substr(pos+1);
229 Path::getStatusInfo(StatusInfo& info) const {
231 if (0 != stat(path.c_str(), &buf)) {
232 ThrowErrno(std::string("Can't get status: ")+path);
234 info.fileSize = buf.st_size;
235 info.modTime.fromEpochTime(buf.st_mtime);
236 info.mode = buf.st_mode;
237 info.user = buf.st_uid;
238 info.group = buf.st_gid;
239 info.isDir = S_ISDIR(buf.st_mode);
240 if (info.isDir && path[path.length()-1] != '/')
244 static bool AddPermissionBits(const std::string& Filename, int bits) {
245 // Get the umask value from the operating system. We want to use it
246 // when changing the file's permissions. Since calling umask() sets
247 // the umask and returns its old value, we must call it a second
248 // time to reset it to the user's preference.
249 int mask = umask(0777); // The arg. to umask is arbitrary.
250 umask(mask); // Restore the umask.
252 // Get the file's current mode.
254 if ((stat(Filename.c_str(), &st)) == -1)
257 // Change the file to have whichever permissions bits from 'bits'
258 // that the umask would not disable.
259 if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)
265 void Path::makeReadable() {
266 if (!AddPermissionBits(path,0444))
267 ThrowErrno(path + ": can't make file readable");
270 void Path::makeWriteable() {
271 if (!AddPermissionBits(path,0222))
272 ThrowErrno(path + ": can't make file writable");
275 void Path::makeExecutable() {
276 if (!AddPermissionBits(path,0111))
277 ThrowErrno(path + ": can't make file executable");
281 Path::getDirectoryContents(std::set<Path>& result) const {
284 DIR* direntries = ::opendir(path.c_str());
286 ThrowErrno(path + ": can't open directory");
289 struct dirent* de = ::readdir(direntries);
291 if (de->d_name[0] != '.') {
292 Path aPath(path + (const char*)de->d_name);
294 if (0 != stat(aPath.path.c_str(), &buf))
295 ThrowErrno(aPath.path + ": can't get status");
296 if (S_ISDIR(buf.st_mode))
298 result.insert(aPath);
300 de = ::readdir(direntries);
303 closedir(direntries);
308 Path::setDirectory(const std::string& a_path) {
309 if (a_path.size() == 0)
313 size_t last = a_path.size() -1;
314 if (a_path[last] != '/')
324 Path::setFile(const std::string& a_path) {
325 if (a_path.size() == 0)
329 size_t last = a_path.size() - 1;
330 while (last > 0 && a_path[last] == '/')
341 Path::appendDirectory(const std::string& dir) {
355 Path::elideDirectory() {
358 size_t slashpos = path.rfind('/',path.size());
359 if (slashpos == 0 || slashpos == std::string::npos)
361 if (slashpos == path.size() - 1)
362 slashpos = path.rfind('/',slashpos-1);
363 if (slashpos == std::string::npos)
365 path.erase(slashpos);
370 Path::appendFile(const std::string& file) {
386 size_t slashpos = path.rfind('/',path.size());
387 if (slashpos == std::string::npos)
389 path.erase(slashpos+1);
394 Path::appendSuffix(const std::string& suffix) {
408 Path::elideSuffix() {
409 if (isDirectory()) return false;
410 size_t dotpos = path.rfind('.',path.size());
411 size_t slashpos = path.rfind('/',path.size());
412 if (slashpos != std::string::npos && dotpos != std::string::npos &&
414 path.erase(dotpos, path.size()-dotpos);
422 Path::createDirectory( bool create_parents) {
423 // Make sure we're dealing with a directory
424 if (!isDirectory()) return false;
426 // Get a writeable copy of the path name
427 char pathname[MAXPATHLEN];
428 path.copy(pathname,MAXPATHLEN);
430 // Null-terminate the last component
431 int lastchar = path.length() - 1 ;
432 if (pathname[lastchar] == '/')
433 pathname[lastchar] = 0;
435 pathname[lastchar+1] = 0;
437 // If we're supposed to create intermediate directories
438 if ( create_parents ) {
439 // Find the end of the initial name component
440 char * next = strchr(pathname,'/');
441 if ( pathname[0] == '/')
442 next = strchr(&pathname[1],'/');
444 // Loop through the directory components until we're done
445 while ( next != 0 ) {
447 if (0 != access(pathname, F_OK | R_OK | W_OK))
448 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
449 ThrowErrno(std::string(pathname) + ": Can't create directory");
451 next = strchr(next+1,'/');
456 if (0 != access(pathname, F_OK | R_OK))
457 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
458 ThrowErrno(std::string(pathname) + ": Can't create directory");
464 // Make sure we're dealing with a file
465 if (!isFile()) return false;
468 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
470 ThrowErrno(path + ": Can't create file");
477 Path::createTemporaryFile(bool reuse_current) {
478 // Make sure we're dealing with a file
482 // Make this into a unique file name
483 makeUnique( reuse_current );
486 int outFile = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
495 Path::destroyDirectory(bool remove_contents) const {
496 // Make sure we're dealing with a directory
497 if (!isDirectory()) return false;
499 // If it doesn't exist, we're done.
500 if (!exists()) return true;
502 if (remove_contents) {
503 // Recursively descend the directory to remove its content
504 std::string cmd("/bin/rm -rf ");
508 // Otherwise, try to just remove the one directory
509 char pathname[MAXPATHLEN];
510 path.copy(pathname,MAXPATHLEN);
511 int lastchar = path.length() - 1 ;
512 if (pathname[lastchar] == '/')
513 pathname[lastchar] = 0;
515 pathname[lastchar+1] = 0;
516 if ( 0 != rmdir(pathname))
517 ThrowErrno(std::string(pathname) + ": Can't destroy directory");
523 Path::destroyFile() const {
524 if (!isFile()) return false;
525 if (0 != unlink(path.c_str()))
526 ThrowErrno(path + ": Can't destroy file");
531 Path::renameFile(const Path& newName) {
532 if (!isFile()) return false;
533 if (0 != rename(path.c_str(), newName.c_str()))
534 ThrowErrno(std::string("can't rename ") + path + " as " +
540 Path::setStatusInfo(const StatusInfo& si) const {
541 if (!isFile()) return false;
543 utb.actime = si.modTime.toPosixTime();
544 utb.modtime = utb.actime;
545 if (0 != ::utime(path.c_str(),&utb))
546 ThrowErrno(path + ": can't set file modification time");
547 if (0 != ::chmod(path.c_str(),si.mode))
548 ThrowErrno(path + ": can't set mode");
553 CopyFile(const sys::Path &Dest, const sys::Path &Src) {
557 inFile = ::open(Src.c_str(), O_RDONLY);
559 ThrowErrno("Cannnot open source file to copy: " + Src.toString());
561 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
563 ThrowErrno("Cannnot create destination file for copy: " +Dest.toString());
565 char Buffer[16*1024];
566 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
568 if (errno != EINTR && errno != EAGAIN)
569 ThrowErrno("Can't read source file: " + Src.toString());
571 char *BufPtr = Buffer;
573 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
574 if (AmtWritten == -1) {
575 if (errno != EINTR && errno != EAGAIN)
576 ThrowErrno("Can't write destination file: " + Dest.toString());
579 BufPtr += AmtWritten;
596 Path::makeUnique(bool reuse_current) {
597 if (reuse_current && !exists())
598 return; // File doesn't exist already, just use it!
600 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
601 // mktemp or our own implementation.
602 char *FNBuffer = (char*) alloca(path.size()+8);
603 path.copy(FNBuffer,path.size());
604 strcpy(FNBuffer+path.size(), "-XXXXXX");
606 #if defined(HAVE_MKSTEMP)
608 if ((TempFD = mkstemp(FNBuffer)) == -1) {
609 ThrowErrno("Cannot make unique filename for '" + path + "'");
612 // We don't need to hold the temp file descriptor... we will trust that no one
613 // will overwrite/delete the file before we can open it again.
618 #elif defined(HAVE_MKTEMP)
619 // If we don't have mkstemp, use the old and obsolete mktemp function.
620 if (mktemp(FNBuffer) == 0) {
621 ThrowErrno("Cannot make unique filename for '" + path + "'");
627 // Okay, looks like we have to do it all by our lonesome.
628 static unsigned FCounter = 0;
629 unsigned offset = path.size() + 1;
630 while ( FCounter < 999999 && exists()) {
631 sprintf(FNBuffer+offset,"%06u",++FCounter);
634 if (FCounter > 999999)
635 throw std::string("Cannot make unique filename for '" + path + "'");