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(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();
160 assert(len < 1024 && "Request for magic string too long");
161 char* buf = (char*) alloca(1 + len);
162 int fd = ::open(path.c_str(),O_RDONLY);
165 if (0 != ::read(fd, buf, len))
172 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
175 assert(len < 1024 && "Request for magic string too long");
176 char* buf = (char*) alloca(1 + len);
177 int fd = ::open(path.c_str(),O_RDONLY);
180 ssize_t bytes_read = ::read(fd, buf, len);
182 if (ssize_t(len) != bytes_read) {
186 Magic.assign(buf,len);
191 Path::isBytecodeFile() const {
194 int fd = ::open(path.c_str(),O_RDONLY);
197 ssize_t bytes_read = ::read(fd, buffer, 4);
202 return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
203 (buffer[3] == 'c' || buffer[3] == 'm'));
207 Path::isArchive() const {
209 return hasMagicNumber("!<arch>\012");
215 Path::exists() const {
216 return 0 == access(path.c_str(), F_OK );
220 Path::readable() const {
221 return 0 == access(path.c_str(), F_OK | R_OK );
225 Path::writable() const {
226 return 0 == access(path.c_str(), F_OK | W_OK );
230 Path::executable() const {
231 return 0 == access(path.c_str(), R_OK | X_OK );
235 Path::getLast() const {
236 // Find the last slash
237 size_t pos = path.rfind('/');
239 // Handle the corner cases
240 if (pos == std::string::npos)
243 // If the last character is a slash
244 if (pos == path.length()-1) {
245 // Find the second to last slash
246 size_t pos2 = path.rfind('/', pos-1);
247 if (pos2 == std::string::npos)
248 return path.substr(0,pos);
250 return path.substr(pos2+1,pos-pos2-1);
252 // Return everything after the last slash
253 return path.substr(pos+1);
257 Path::getStatusInfo(StatusInfo& info) const {
259 if (0 != stat(path.c_str(), &buf)) {
260 ThrowErrno(std::string("Can't get status: ")+path);
262 info.fileSize = buf.st_size;
263 info.modTime.fromEpochTime(buf.st_mtime);
264 info.mode = buf.st_mode;
265 info.user = buf.st_uid;
266 info.group = buf.st_gid;
267 info.isDir = S_ISDIR(buf.st_mode);
268 if (info.isDir && path[path.length()-1] != '/')
273 Path::getDirectoryContents(std::set<Path>& result) const {
276 DIR* direntries = ::opendir(path.c_str());
278 ThrowErrno(path + ": can't open directory");
281 struct dirent* de = ::readdir(direntries);
283 if (de->d_name[0] != '.') {
284 Path aPath(path + (const char*)de->d_name);
286 if (0 != stat(aPath.path.c_str(), &buf))
287 ThrowErrno(aPath.path + ": can't get status");
288 if (S_ISDIR(buf.st_mode))
290 result.insert(aPath);
292 de = ::readdir(direntries);
295 closedir(direntries);
300 Path::setDirectory(const std::string& a_path) {
301 if (a_path.size() == 0)
305 size_t last = a_path.size() -1;
306 if (last != 0 && a_path[last] != '/')
316 Path::setFile(const std::string& a_path) {
317 if (a_path.size() == 0)
321 size_t last = a_path.size() - 1;
322 while (last > 0 && a_path[last] == '/')
333 Path::appendDirectory(const std::string& dir) {
347 Path::elideDirectory() {
350 size_t slashpos = path.rfind('/',path.size());
351 if (slashpos == 0 || slashpos == std::string::npos)
353 if (slashpos == path.size() - 1)
354 slashpos = path.rfind('/',slashpos-1);
355 if (slashpos == std::string::npos)
357 path.erase(slashpos);
362 Path::appendFile(const std::string& file) {
378 size_t slashpos = path.rfind('/',path.size());
379 if (slashpos == std::string::npos)
381 path.erase(slashpos+1);
386 Path::appendSuffix(const std::string& suffix) {
400 Path::elideSuffix() {
401 if (isDirectory()) return false;
402 size_t dotpos = path.rfind('.',path.size());
403 size_t slashpos = path.rfind('/',path.size());
404 if (slashpos != std::string::npos && dotpos != std::string::npos &&
406 path.erase(dotpos, path.size()-dotpos);
414 Path::createDirectory( bool create_parents) {
415 // Make sure we're dealing with a directory
416 if (!isDirectory()) return false;
418 // Get a writeable copy of the path name
419 char pathname[MAXPATHLEN];
420 path.copy(pathname,MAXPATHLEN);
422 // Null-terminate the last component
423 int lastchar = path.length() - 1 ;
424 if (pathname[lastchar] == '/')
425 pathname[lastchar] = 0;
427 pathname[lastchar+1] = 0;
429 // If we're supposed to create intermediate directories
430 if ( create_parents ) {
431 // Find the end of the initial name component
432 char * next = strchr(pathname,'/');
433 if ( pathname[0] == '/')
434 next = strchr(&pathname[1],'/');
436 // Loop through the directory components until we're done
437 while ( next != 0 ) {
439 if (0 != access(pathname, F_OK | R_OK | W_OK))
440 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
441 ThrowErrno(std::string(pathname) + ": Can't create directory");
443 next = strchr(next+1,'/');
448 if (0 != access(pathname, F_OK | R_OK))
449 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
450 ThrowErrno(std::string(pathname) + ": Can't create directory");
456 // Make sure we're dealing with a file
457 if (!isFile()) return false;
460 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
462 ThrowErrno(path + ": Can't create file");
469 Path::createTemporaryFile() {
470 // Make sure we're dealing with a file
471 if (!isFile()) return false;
473 // Append the filename filler
474 char pathname[MAXPATHLEN];
475 path.copy(pathname,MAXPATHLEN);
476 pathname[path.length()] = 0;
477 strcat(pathname,"XXXXXX");
478 int fd = ::mkstemp(pathname);
480 ThrowErrno(path + ": Can't create temporary file");
488 Path::destroyDirectory(bool remove_contents) {
489 // Make sure we're dealing with a directory
490 if (!isDirectory()) return false;
492 // If it doesn't exist, we're done.
493 if (!exists()) return true;
495 if (remove_contents) {
496 // Recursively descend the directory to remove its content
497 std::string cmd("/bin/rm -rf ");
501 // Otherwise, try to just remove the one directory
502 char pathname[MAXPATHLEN];
503 path.copy(pathname,MAXPATHLEN);
504 int lastchar = path.length() - 1 ;
505 if (pathname[lastchar] == '/')
506 pathname[lastchar] = 0;
508 pathname[lastchar+1] = 0;
509 if ( 0 != rmdir(pathname))
510 ThrowErrno(std::string(pathname) + ": Can't destroy directory");
516 Path::destroyFile() {
517 if (!isFile()) return false;
518 if (0 != unlink(path.c_str()))
519 ThrowErrno(path + ": Can't destroy file");
524 Path::renameFile(const Path& newName) {
525 if (!isFile()) return false;
526 if (0 != rename(path.c_str(), newName.c_str()))
527 ThrowErrno(std::string("can't rename ") + path + " as " +
533 Path::setStatusInfo(const StatusInfo& si) const {
534 if (!isFile()) return false;
536 utb.actime = si.modTime.toPosixTime();
537 utb.modtime = utb.actime;
538 if (0 != ::utime(path.c_str(),&utb))
539 ThrowErrno(path + ": can't set file modification time");
540 if (0 != ::chmod(path.c_str(),si.mode))
541 ThrowErrno(path + ": can't set mode");