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) + "bytecode-libs/");
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::GetLLVMConfigDir() {
114 if (result.setDirectory(LLVM_ETCDIR))
116 return GetLLVMDefaultConfigDir();
120 Path::GetUserHomeDirectory() {
121 const char* home = getenv("HOME");
124 if (result.setDirectory(home))
127 return GetRootDirectory();
131 Path::isFile() const {
132 return (isValid() && path[path.length()-1] != '/');
136 Path::isDirectory() const {
137 return (isValid() && path[path.length()-1] == '/');
141 Path::getBasename() const {
142 // Find the last slash
143 size_t slash = path.rfind('/');
144 if (slash == std::string::npos)
149 return path.substr(slash, path.rfind('.'));
152 bool Path::hasMagicNumber(const std::string &Magic) const {
153 size_t len = Magic.size();
154 assert(len < 1024 && "Request for magic string too long");
155 char* buf = (char*) alloca(1 + len);
156 int fd = ::open(path.c_str(),O_RDONLY);
159 size_t read_len = ::read(fd, buf, len);
167 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
170 assert(len < 1024 && "Request for magic string too long");
171 char* buf = (char*) alloca(1 + len);
172 int fd = ::open(path.c_str(),O_RDONLY);
175 ssize_t bytes_read = ::read(fd, buf, len);
177 if (ssize_t(len) != bytes_read) {
181 Magic.assign(buf,len);
186 Path::isBytecodeFile() const {
189 int fd = ::open(path.c_str(),O_RDONLY);
192 ssize_t bytes_read = ::read(fd, buffer, 4);
197 return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
198 (buffer[3] == 'c' || buffer[3] == 'm'));
202 Path::exists() const {
203 return 0 == access(path.c_str(), F_OK );
207 Path::readable() const {
208 return 0 == access(path.c_str(), F_OK | R_OK );
212 Path::writable() const {
213 return 0 == access(path.c_str(), F_OK | W_OK );
217 Path::executable() const {
218 return 0 == access(path.c_str(), R_OK | X_OK );
222 Path::getLast() const {
223 // Find the last slash
224 size_t pos = path.rfind('/');
226 // Handle the corner cases
227 if (pos == std::string::npos)
230 // If the last character is a slash
231 if (pos == path.length()-1) {
232 // Find the second to last slash
233 size_t pos2 = path.rfind('/', pos-1);
234 if (pos2 == std::string::npos)
235 return path.substr(0,pos);
237 return path.substr(pos2+1,pos-pos2-1);
239 // Return everything after the last slash
240 return path.substr(pos+1);
244 Path::getStatusInfo(StatusInfo& info) const {
246 if (0 != stat(path.c_str(), &buf)) {
247 ThrowErrno(std::string("Can't get status: ")+path);
249 info.fileSize = buf.st_size;
250 info.modTime.fromEpochTime(buf.st_mtime);
251 info.mode = buf.st_mode;
252 info.user = buf.st_uid;
253 info.group = buf.st_gid;
254 info.isDir = S_ISDIR(buf.st_mode);
255 if (info.isDir && path[path.length()-1] != '/')
259 static bool AddPermissionBits(const std::string& Filename, int bits) {
260 // Get the umask value from the operating system. We want to use it
261 // when changing the file's permissions. Since calling umask() sets
262 // the umask and returns its old value, we must call it a second
263 // time to reset it to the user's preference.
264 int mask = umask(0777); // The arg. to umask is arbitrary.
265 umask(mask); // Restore the umask.
267 // Get the file's current mode.
269 if ((stat(Filename.c_str(), &st)) == -1)
272 // Change the file to have whichever permissions bits from 'bits'
273 // that the umask would not disable.
274 if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)
280 void Path::makeReadable() {
281 if (!AddPermissionBits(path,0444))
282 ThrowErrno(path + ": can't make file readable");
285 void Path::makeWriteable() {
286 if (!AddPermissionBits(path,0222))
287 ThrowErrno(path + ": can't make file writable");
290 void Path::makeExecutable() {
291 if (!AddPermissionBits(path,0111))
292 ThrowErrno(path + ": can't make file executable");
296 Path::getDirectoryContents(std::set<Path>& result) const {
299 DIR* direntries = ::opendir(path.c_str());
301 ThrowErrno(path + ": can't open directory");
304 struct dirent* de = ::readdir(direntries);
306 if (de->d_name[0] != '.') {
307 Path aPath(path + (const char*)de->d_name);
309 if (0 != stat(aPath.path.c_str(), &buf))
310 ThrowErrno(aPath.path + ": can't get status");
311 if (S_ISDIR(buf.st_mode))
313 result.insert(aPath);
315 de = ::readdir(direntries);
318 closedir(direntries);
323 Path::setDirectory(const std::string& a_path) {
324 if (a_path.size() == 0)
328 size_t last = a_path.size() -1;
329 if (a_path[last] != '/')
339 Path::setFile(const std::string& a_path) {
340 if (a_path.size() == 0)
344 size_t last = a_path.size() - 1;
345 while (last > 0 && a_path[last] == '/')
356 Path::appendDirectory(const std::string& dir) {
370 Path::elideDirectory() {
373 size_t slashpos = path.rfind('/',path.size());
374 if (slashpos == 0 || slashpos == std::string::npos)
376 if (slashpos == path.size() - 1)
377 slashpos = path.rfind('/',slashpos-1);
378 if (slashpos == std::string::npos)
380 path.erase(slashpos);
385 Path::appendFile(const std::string& file) {
401 size_t slashpos = path.rfind('/',path.size());
402 if (slashpos == std::string::npos)
404 path.erase(slashpos+1);
409 Path::appendSuffix(const std::string& suffix) {
423 Path::elideSuffix() {
424 if (isDirectory()) return false;
425 size_t dotpos = path.rfind('.',path.size());
426 size_t slashpos = path.rfind('/',path.size());
427 if (slashpos != std::string::npos && dotpos != std::string::npos &&
429 path.erase(dotpos, path.size()-dotpos);
437 Path::createDirectory( bool create_parents) {
438 // Make sure we're dealing with a directory
439 if (!isDirectory()) return false;
441 // Get a writeable copy of the path name
442 char pathname[MAXPATHLEN];
443 path.copy(pathname,MAXPATHLEN);
445 // Null-terminate the last component
446 int lastchar = path.length() - 1 ;
447 if (pathname[lastchar] == '/')
448 pathname[lastchar] = 0;
450 pathname[lastchar+1] = 0;
452 // If we're supposed to create intermediate directories
453 if ( create_parents ) {
454 // Find the end of the initial name component
455 char * next = strchr(pathname,'/');
456 if ( pathname[0] == '/')
457 next = strchr(&pathname[1],'/');
459 // Loop through the directory components until we're done
460 while ( next != 0 ) {
462 if (0 != access(pathname, F_OK | R_OK | W_OK))
463 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
464 ThrowErrno(std::string(pathname) + ": Can't create directory");
466 next = strchr(next+1,'/');
471 if (0 != access(pathname, F_OK | R_OK))
472 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
473 ThrowErrno(std::string(pathname) + ": Can't create directory");
479 // Make sure we're dealing with a file
480 if (!isFile()) return false;
483 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
485 ThrowErrno(path + ": Can't create file");
492 Path::createTemporaryFile() {
493 // Make sure we're dealing with a file
494 if (!isFile()) return false;
496 // Append the filename filler
497 char pathname[MAXPATHLEN];
498 path.copy(pathname,MAXPATHLEN);
499 pathname[path.length()] = 0;
500 strcat(pathname,"XXXXXX");
501 int fd = ::mkstemp(pathname);
503 ThrowErrno(path + ": Can't create temporary file");
511 Path::destroyDirectory(bool remove_contents) {
512 // Make sure we're dealing with a directory
513 if (!isDirectory()) return false;
515 // If it doesn't exist, we're done.
516 if (!exists()) return true;
518 if (remove_contents) {
519 // Recursively descend the directory to remove its content
520 std::string cmd("/bin/rm -rf ");
524 // Otherwise, try to just remove the one directory
525 char pathname[MAXPATHLEN];
526 path.copy(pathname,MAXPATHLEN);
527 int lastchar = path.length() - 1 ;
528 if (pathname[lastchar] == '/')
529 pathname[lastchar] = 0;
531 pathname[lastchar+1] = 0;
532 if ( 0 != rmdir(pathname))
533 ThrowErrno(std::string(pathname) + ": Can't destroy directory");
539 Path::destroyFile() {
540 if (!isFile()) return false;
541 if (0 != unlink(path.c_str()))
542 ThrowErrno(path + ": Can't destroy file");
547 Path::renameFile(const Path& newName) {
548 if (!isFile()) return false;
549 if (0 != rename(path.c_str(), newName.c_str()))
550 ThrowErrno(std::string("can't rename ") + path + " as " +
556 Path::setStatusInfo(const StatusInfo& si) const {
557 if (!isFile()) return false;
559 utb.actime = si.modTime.toPosixTime();
560 utb.modtime = utb.actime;
561 if (0 != ::utime(path.c_str(),&utb))
562 ThrowErrno(path + ": can't set file modification time");
563 if (0 != ::chmod(path.c_str(),si.mode))
564 ThrowErrno(path + ": can't set mode");