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>
30 Path::Path(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 inline bool IsLibrary(Path& path, const std::string& basename) {
50 if (path.appendFile(std::string("lib") + basename)) {
51 if (path.appendSuffix(Path::GetDLLSuffix()) && path.readable())
53 else if (path.elideSuffix() && path.appendSuffix("a") && path.readable())
55 else if (path.elideSuffix() && path.appendSuffix("o") && path.readable())
57 else if (path.elideSuffix() && path.appendSuffix("bc") && path.readable())
59 } else if (path.elideFile() && path.appendFile(basename)) {
60 if (path.appendSuffix(Path::GetDLLSuffix()) && path.readable())
62 else if (path.elideSuffix() && path.appendSuffix("a") && path.readable())
64 else if (path.elideSuffix() && path.appendSuffix("o") && path.readable())
66 else if (path.elideSuffix() && path.appendSuffix("bc") && path.readable())
74 Path::GetLibraryPath(const std::string& basename,
75 const std::vector<std::string>& LibPaths) {
78 // Try the paths provided
79 for (std::vector<std::string>::const_iterator I = LibPaths.begin(),
80 E = LibPaths.end(); I != E; ++I ) {
81 if (result.setDirectory(*I) && IsLibrary(result,basename))
85 // Try the LLVM lib directory in the LLVM install area
86 if (result.setDirectory(LLVM_LIBDIR) && IsLibrary(result,basename))
90 if (result.setDirectory("/usr/lib/") && IsLibrary(result,basename))
94 if (result.setDirectory("/lib/") && IsLibrary(result,basename))
97 // Can't find it, give up and return invalid path.
103 Path::GetSystemLibraryPath1() {
104 return Path("/lib/");
108 Path::GetSystemLibraryPath2() {
109 return Path("/usr/lib/");
113 Path::GetLLVMDefaultConfigDir() {
114 return Path("/etc/llvm/");
118 Path::GetLLVMConfigDir() {
120 if (result.setDirectory(LLVM_ETCDIR))
122 return GetLLVMDefaultConfigDir();
126 Path::GetUserHomeDirectory() {
127 const char* home = getenv("HOME");
130 if (result.setDirectory(home))
133 return GetRootDirectory();
137 Path::isFile() const {
138 return (isValid() && path[path.length()-1] != '/');
142 Path::isDirectory() const {
143 return (isValid() && path[path.length()-1] == '/');
147 Path::getBasename() const {
148 // Find the last slash
149 size_t slash = path.rfind('/');
150 if (slash == std::string::npos)
155 return path.substr(slash, path.rfind('.'));
158 bool Path::hasMagicNumber(const std::string &Magic) const {
159 size_t len = Magic.size();
161 std::ifstream f(path.c_str());
168 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
172 std::ifstream f(path.c_str());
180 Path::isBytecodeFile() const {
183 std::ifstream f(path.c_str());
186 ThrowErrno("can't read file signature");
188 return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
189 (buffer[3] == 'c' || buffer[3] == 'm'));
193 Path::isArchive() const {
195 return hasMagicNumber("!<arch>\012");
201 Path::exists() const {
202 return 0 == access(path.c_str(), F_OK );
206 Path::readable() const {
207 return 0 == access(path.c_str(), F_OK | R_OK );
211 Path::writable() const {
212 return 0 == access(path.c_str(), F_OK | W_OK );
216 Path::executable() const {
217 return 0 == access(path.c_str(), R_OK | X_OK );
221 Path::getLast() const {
222 // Find the last slash
223 size_t pos = path.rfind('/');
225 // Handle the corner cases
226 if (pos == std::string::npos)
229 // If the last character is a slash
230 if (pos == path.length()-1) {
231 // Find the second to last slash
232 size_t pos2 = path.rfind('/', pos-1);
233 if (pos2 == std::string::npos)
234 return path.substr(0,pos);
236 return path.substr(pos2+1,pos-pos2-1);
238 // Return everything after the last slash
239 return path.substr(pos+1);
243 Path::getStatusInfo(StatusInfo& info) {
244 if (!isFile() || !readable())
247 if (0 != stat(path.c_str(), &buf)) {
248 ThrowErrno(std::string("Can't get status: ")+path);
250 info.fileSize = buf.st_size;
251 info.modTime.fromEpochTime(buf.st_mtime);
252 info.mode = buf.st_mode;
253 info.user = buf.st_uid;
254 info.group = buf.st_gid;
255 info.isDir = S_ISDIR(buf.st_mode);
256 if (info.isDir && path[path.length()-1] != '/')
262 Path::getDirectoryContents(Vector& result) const {
265 DIR* direntries = ::opendir(path.c_str());
267 ThrowErrno(path + ": can't open directory");
270 struct dirent* de = ::readdir(direntries);
272 if (de->d_name[0] != '.') {
273 Path aPath(path + (const char*)de->d_name);
275 if (0 != stat(aPath.path.c_str(), &buf))
276 ThrowErrno(aPath.path + ": can't get status");
277 if (S_ISDIR(buf.st_mode))
279 result.push_back(aPath);
281 de = ::readdir(direntries);
284 closedir(direntries);
289 Path::setDirectory(const std::string& a_path) {
290 if (a_path.size() == 0)
294 size_t last = a_path.size() -1;
295 if (last != 0 && a_path[last] != '/')
305 Path::setFile(const std::string& a_path) {
306 if (a_path.size() == 0)
310 size_t last = a_path.size() - 1;
311 while (last > 0 && a_path[last] == '/')
322 Path::appendDirectory(const std::string& dir) {
336 Path::elideDirectory() {
339 size_t slashpos = path.rfind('/',path.size());
340 if (slashpos == 0 || slashpos == std::string::npos)
342 if (slashpos == path.size() - 1)
343 slashpos = path.rfind('/',slashpos-1);
344 if (slashpos == std::string::npos)
346 path.erase(slashpos);
351 Path::appendFile(const std::string& file) {
367 size_t slashpos = path.rfind('/',path.size());
368 if (slashpos == std::string::npos)
370 path.erase(slashpos+1);
375 Path::appendSuffix(const std::string& suffix) {
389 Path::elideSuffix() {
390 if (isDirectory()) return false;
391 size_t dotpos = path.rfind('.',path.size());
392 size_t slashpos = path.rfind('/',path.size());
393 if (slashpos != std::string::npos && dotpos != std::string::npos &&
395 path.erase(dotpos, path.size()-dotpos);
403 Path::createDirectory( bool create_parents) {
404 // Make sure we're dealing with a directory
405 if (!isDirectory()) return false;
407 // Get a writeable copy of the path name
408 char pathname[MAXPATHLEN];
409 path.copy(pathname,MAXPATHLEN);
411 // Null-terminate the last component
412 int lastchar = path.length() - 1 ;
413 if (pathname[lastchar] == '/')
414 pathname[lastchar] = 0;
416 pathname[lastchar+1] = 0;
418 // If we're supposed to create intermediate directories
419 if ( create_parents ) {
420 // Find the end of the initial name component
421 char * next = strchr(pathname,'/');
422 if ( pathname[0] == '/')
423 next = strchr(&pathname[1],'/');
425 // Loop through the directory components until we're done
426 while ( next != 0 ) {
428 if (0 != access(pathname, F_OK | R_OK | W_OK))
429 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
430 ThrowErrno(std::string(pathname) + ": Can't create directory");
432 next = strchr(next+1,'/');
437 if (0 != access(pathname, F_OK | R_OK))
438 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
439 ThrowErrno(std::string(pathname) + ": Can't create directory");
445 // Make sure we're dealing with a file
446 if (!isFile()) return false;
449 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
451 ThrowErrno(path + ": Can't create file");
458 Path::createTemporaryFile() {
459 // Make sure we're dealing with a file
460 if (!isFile()) return false;
462 // Append the filename filler
463 char pathname[MAXPATHLEN];
464 path.copy(pathname,MAXPATHLEN);
465 pathname[path.length()] = 0;
466 strcat(pathname,"XXXXXX");
467 int fd = ::mkstemp(pathname);
469 ThrowErrno(path + ": Can't create temporary file");
477 Path::destroyDirectory(bool remove_contents) {
478 // Make sure we're dealing with a directory
479 if (!isDirectory()) return false;
481 // If it doesn't exist, we're done.
482 if (!exists()) return true;
484 if (remove_contents) {
485 // Recursively descend the directory to remove its content
486 std::string cmd("/bin/rm -rf ");
490 // Otherwise, try to just remove the one directory
491 char pathname[MAXPATHLEN];
492 path.copy(pathname,MAXPATHLEN);
493 int lastchar = path.length() - 1 ;
494 if (pathname[lastchar] == '/')
495 pathname[lastchar] = 0;
497 pathname[lastchar+1] = 0;
498 if ( 0 != rmdir(pathname))
499 ThrowErrno(std::string(pathname) + ": Can't destroy directory");
505 Path::destroyFile() {
506 if (!isFile()) return false;
507 if (0 != unlink(path.c_str()))
508 ThrowErrno(path + ": Can't destroy file");
513 Path::renameFile(const Path& newName) {
514 if (!isFile()) return false;
515 if (0 != rename(path.c_str(), newName.c_str()))
516 ThrowErrno(std::string("can't rename ") + path + " as " + newName.get());
521 Path::setStatusInfo(const StatusInfo& si) const {
522 if (!isFile()) return false;
524 utb.actime = si.modTime.toPosixTime();
525 utb.modtime = utb.actime;
526 if (0 != ::utime(path.c_str(),&utb))
527 ThrowErrno(path + ": can't set file modification time");
528 if (0 != ::chmod(path.c_str(),si.mode))
529 ThrowErrno(path + ": can't set mode");