1 //===- llvm/System/Unix/Path.cpp - Unix Path Implementation -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/alloca.h"
35 # define NAMLEN(dirent) strlen((dirent)->d_name)
37 # define dirent direct
38 # define NAMLEN(dirent) (dirent)->d_namlen
40 # include <sys/ndir.h>
54 // Put in a hack for Cygwin which falsely reports that the mkdtemp function
55 // is available when it is not.
61 inline bool lastIsSlash(const std::string& path) {
62 return !path.empty() && path[path.length() - 1] == '/';
70 extern const char sys::PathSeparator = ':';
73 Path::isValid() const {
74 // Check some obvious things
77 else if (path.length() >= MAXPATHLEN)
80 // Check that the characters are ascii chars
81 size_t len = path.length();
83 while (i < len && isascii(path[i]))
89 Path::isAbsolute() const {
92 return path[0] == '/';
95 Path::GetRootDirectory() {
102 Path::GetTemporaryDirectory(std::string* ErrMsg ) {
103 #if defined(HAVE_MKDTEMP)
104 // The best way is with mkdtemp but that's not available on many systems,
105 // Linux and FreeBSD have it. Others probably won't.
106 char pathname[MAXPATHLEN];
107 strcpy(pathname,"/tmp/llvm_XXXXXX");
108 if (0 == mkdtemp(pathname)) {
110 std::string(pathname) + ": can't create temporary directory");
114 result.set(pathname);
115 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
117 #elif defined(HAVE_MKSTEMP)
118 // If no mkdtemp is available, mkstemp can be used to create a temporary file
119 // which is then removed and created as a directory. We prefer this over
120 // mktemp because of mktemp's inherent security and threading risks. We still
121 // have a slight race condition from the time the temporary file is created to
122 // the time it is re-created as a directoy.
123 char pathname[MAXPATHLEN];
124 strcpy(pathname, "/tmp/llvm_XXXXXX");
126 if (-1 == (fd = mkstemp(pathname))) {
128 std::string(pathname) + ": can't create temporary directory");
132 ::unlink(pathname); // start race condition, ignore errors
133 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
135 std::string(pathname) + ": can't create temporary directory");
139 result.set(pathname);
140 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
142 #elif defined(HAVE_MKTEMP)
143 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
144 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
145 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
146 // the XXXXXX with the pid of the process and a letter. That leads to only
147 // twenty six temporary files that can be generated.
148 char pathname[MAXPATHLEN];
149 strcpy(pathname, "/tmp/llvm_XXXXXX");
150 char *TmpName = ::mktemp(pathname);
153 std::string(TmpName) + ": can't create unique directory name");
156 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
158 std::string(TmpName) + ": can't create temporary directory");
163 assert(result.isValid() && "mktemp didn't create a valid pathname!");
166 // This is the worst case implementation. tempnam(3) leaks memory unless its
167 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
168 // issues. The mktemp(3) function doesn't have enough variability in the
169 // temporary name generated. So, we provide our own implementation that
170 // increments an integer from a random number seeded by the current time. This
171 // should be sufficiently unique that we don't have many collisions between
172 // processes. Generally LLVM processes don't run very long and don't use very
173 // many temporary files so this shouldn't be a big issue for LLVM.
174 static time_t num = ::time(0);
175 char pathname[MAXPATHLEN];
178 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
179 } while ( 0 == access(pathname, F_OK ) );
180 if (-1 == ::mkdir(pathname, S_IRWXU)) {
182 std::string(pathname) + ": can't create temporary directory");
186 result.set(pathname);
187 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
193 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
194 #ifdef LTDL_SHLIBPATH_VAR
195 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
197 getPathList(env_var,Paths);
200 // FIXME: Should this look at LD_LIBRARY_PATH too?
201 Paths.push_back(sys::Path("/usr/local/lib/"));
202 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
203 Paths.push_back(sys::Path("/usr/lib/"));
204 Paths.push_back(sys::Path("/lib/"));
208 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
209 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
211 getPathList(env_var,Paths);
216 if (tmpPath.set(LLVM_LIBDIR))
217 if (tmpPath.canRead())
218 Paths.push_back(tmpPath);
221 GetSystemLibraryPaths(Paths);
225 Path::GetLLVMDefaultConfigDir() {
226 return Path("/etc/llvm/");
230 Path::GetUserHomeDirectory() {
231 const char* home = getenv("HOME");
234 if (result.set(home))
237 return GetRootDirectory();
241 Path::GetCurrentDirectory() {
242 char pathname[MAXPATHLEN];
243 if (!getcwd(pathname,MAXPATHLEN)) {
244 assert (false && "Could not query current working directory.");
248 return Path(pathname);
251 /// GetMainExecutable - Return the path to the main executable, given the
252 /// value of argv[0] from program startup.
253 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
254 #if defined(__CYGWIN__)
256 snprintf(exe_link, sizeof(exe_link), "/proc/%d/exe", getpid());
257 char exe_path[MAXPATHLEN];
258 ssize_t len = readlink(exe_link, exe_path, sizeof(exe_path));
259 if (len > 0 && len < MAXPATHLEN - 1) {
260 exe_path[len] = '\0';
261 return Path(std::string(exe_path));
263 #elif defined(HAVE_DLFCN_H)
264 // Use dladdr to get executable path if available.
266 int err = dladdr(MainAddr, &DLInfo);
268 return Path(std::string(DLInfo.dli_fname));
275 Path::getBasename() const {
276 // Find the last slash
277 size_t slash = path.rfind('/');
278 if (slash == std::string::npos)
283 size_t dot = path.rfind('.');
284 if (dot == std::string::npos || dot < slash)
285 return path.substr(slash);
287 return path.substr(slash, dot - slash);
290 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
291 assert(len < 1024 && "Request for magic string too long");
292 char* buf = (char*) alloca(1 + len);
293 int fd = ::open(path.c_str(), O_RDONLY);
296 ssize_t bytes_read = ::read(fd, buf, len);
298 if (ssize_t(len) != bytes_read) {
302 Magic.assign(buf,len);
307 Path::exists() const {
308 return 0 == access(path.c_str(), F_OK );
312 Path::isDirectory() const {
314 if (0 != stat(path.c_str(), &buf))
316 return buf.st_mode & S_IFDIR ? true : false;
320 Path::canRead() const {
321 return 0 == access(path.c_str(), F_OK | R_OK );
325 Path::canWrite() const {
326 return 0 == access(path.c_str(), F_OK | W_OK );
330 Path::canExecute() const {
331 if (0 != access(path.c_str(), R_OK | X_OK ))
334 if (0 != stat(path.c_str(), &buf))
336 if (!S_ISREG(buf.st_mode))
342 Path::getLast() const {
343 // Find the last slash
344 size_t pos = path.rfind('/');
346 // Handle the corner cases
347 if (pos == std::string::npos)
350 // If the last character is a slash
351 if (pos == path.length()-1) {
352 // Find the second to last slash
353 size_t pos2 = path.rfind('/', pos-1);
354 if (pos2 == std::string::npos)
355 return path.substr(0,pos);
357 return path.substr(pos2+1,pos-pos2-1);
359 // Return everything after the last slash
360 return path.substr(pos+1);
364 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
365 if (!fsIsValid || update) {
367 if (0 != stat(path.c_str(), &buf)) {
368 MakeErrMsg(ErrStr, path + ": can't get status of file");
371 status.fileSize = buf.st_size;
372 status.modTime.fromEpochTime(buf.st_mtime);
373 status.mode = buf.st_mode;
374 status.user = buf.st_uid;
375 status.group = buf.st_gid;
376 status.uniqueID = uint64_t(buf.st_ino);
377 status.isDir = S_ISDIR(buf.st_mode);
378 status.isFile = S_ISREG(buf.st_mode);
384 static bool AddPermissionBits(const Path &File, int bits) {
385 // Get the umask value from the operating system. We want to use it
386 // when changing the file's permissions. Since calling umask() sets
387 // the umask and returns its old value, we must call it a second
388 // time to reset it to the user's preference.
389 int mask = umask(0777); // The arg. to umask is arbitrary.
390 umask(mask); // Restore the umask.
392 // Get the file's current mode.
394 if (0 != stat(File.toString().c_str(), &buf))
396 // Change the file to have whichever permissions bits from 'bits'
397 // that the umask would not disable.
398 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
403 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
404 if (!AddPermissionBits(*this, 0444))
405 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
409 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
410 if (!AddPermissionBits(*this, 0222))
411 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
415 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
416 if (!AddPermissionBits(*this, 0111))
417 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
422 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
423 DIR* direntries = ::opendir(path.c_str());
425 return MakeErrMsg(ErrMsg, path + ": can't open directory");
427 std::string dirPath = path;
428 if (!lastIsSlash(dirPath))
432 struct dirent* de = ::readdir(direntries);
433 for ( ; de != 0; de = ::readdir(direntries)) {
434 if (de->d_name[0] != '.') {
435 Path aPath(dirPath + (const char*)de->d_name);
437 if (0 != lstat(aPath.path.c_str(), &st)) {
438 if (S_ISLNK(st.st_mode))
439 continue; // dangling symlink -- ignore
440 return MakeErrMsg(ErrMsg,
441 aPath.path + ": can't determine file object type");
443 result.insert(aPath);
447 closedir(direntries);
452 Path::set(const std::string& a_path) {
455 std::string save(path);
465 Path::appendComponent(const std::string& name) {
468 std::string save(path);
469 if (!lastIsSlash(path))
480 Path::eraseComponent() {
481 size_t slashpos = path.rfind('/',path.size());
482 if (slashpos == 0 || slashpos == std::string::npos) {
486 if (slashpos == path.size() - 1)
487 slashpos = path.rfind('/',slashpos-1);
488 if (slashpos == std::string::npos) {
492 path.erase(slashpos);
497 Path::appendSuffix(const std::string& suffix) {
498 std::string save(path);
509 Path::eraseSuffix() {
510 std::string save = path;
511 size_t dotpos = path.rfind('.',path.size());
512 size_t slashpos = path.rfind('/',path.size());
513 if (dotpos != std::string::npos) {
514 if (slashpos == std::string::npos || dotpos > slashpos+1) {
515 path.erase(dotpos, path.size()-dotpos);
525 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
526 // Get a writeable copy of the path name
527 char pathname[MAXPATHLEN];
528 path.copy(pathname,MAXPATHLEN);
530 // Null-terminate the last component
531 int lastchar = path.length() - 1 ;
532 if (pathname[lastchar] == '/')
533 pathname[lastchar] = 0;
535 pathname[lastchar+1] = 0;
537 // If we're supposed to create intermediate directories
538 if ( create_parents ) {
539 // Find the end of the initial name component
540 char * next = strchr(pathname,'/');
541 if ( pathname[0] == '/')
542 next = strchr(&pathname[1],'/');
544 // Loop through the directory components until we're done
545 while ( next != 0 ) {
547 if (0 != access(pathname, F_OK | R_OK | W_OK))
548 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
549 return MakeErrMsg(ErrMsg,
550 std::string(pathname) + ": can't create directory");
553 next = strchr(next+1,'/');
558 if (0 != access(pathname, F_OK | R_OK))
559 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
560 return MakeErrMsg(ErrMsg,
561 std::string(pathname) + ": can't create directory");
567 Path::createFileOnDisk(std::string* ErrMsg) {
569 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
571 return MakeErrMsg(ErrMsg, path + ": can't create file");
577 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
578 // Make this into a unique file name
579 if (makeUnique( reuse_current, ErrMsg ))
583 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
585 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
591 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
592 // Get the status so we can determin if its a file or directory
594 if (0 != stat(path.c_str(), &buf)) {
595 MakeErrMsg(ErrStr, path + ": can't get status of file");
599 // Note: this check catches strange situations. In all cases, LLVM should
600 // only be involved in the creation and deletion of regular files. This
601 // check ensures that what we're trying to erase is a regular file. It
602 // effectively prevents LLVM from erasing things like /dev/null, any block
603 // special file, or other things that aren't "regular" files.
604 if (S_ISREG(buf.st_mode)) {
605 if (unlink(path.c_str()) != 0)
606 return MakeErrMsg(ErrStr, path + ": can't destroy file");
610 if (!S_ISDIR(buf.st_mode)) {
611 if (ErrStr) *ErrStr = "not a file or directory";
615 if (remove_contents) {
616 // Recursively descend the directory to remove its contents.
617 std::string cmd = "/bin/rm -rf " + path;
622 // Otherwise, try to just remove the one directory.
623 char pathname[MAXPATHLEN];
624 path.copy(pathname, MAXPATHLEN);
625 int lastchar = path.length() - 1 ;
626 if (pathname[lastchar] == '/')
627 pathname[lastchar] = 0;
629 pathname[lastchar+1] = 0;
631 if (rmdir(pathname) != 0)
632 return MakeErrMsg(ErrStr,
633 std::string(pathname) + ": can't erase directory");
638 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
639 if (0 != ::rename(path.c_str(), newName.c_str()))
640 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
641 newName.toString() + "' ");
646 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
648 utb.actime = si.modTime.toPosixTime();
649 utb.modtime = utb.actime;
650 if (0 != ::utime(path.c_str(),&utb))
651 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
652 if (0 != ::chmod(path.c_str(),si.mode))
653 return MakeErrMsg(ErrStr, path + ": can't set mode");
658 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
661 inFile = ::open(Src.c_str(), O_RDONLY);
663 return MakeErrMsg(ErrMsg, Src.toString() +
664 ": can't open source file to copy");
666 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
669 return MakeErrMsg(ErrMsg, Dest.toString() +
670 ": can't create destination file for copy");
673 char Buffer[16*1024];
674 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
676 if (errno != EINTR && errno != EAGAIN) {
679 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file: ");
682 char *BufPtr = Buffer;
684 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
685 if (AmtWritten == -1) {
686 if (errno != EINTR && errno != EAGAIN) {
689 return MakeErrMsg(ErrMsg, Dest.toString() +
690 ": can't write destination file: ");
694 BufPtr += AmtWritten;
705 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
706 if (reuse_current && !exists())
707 return false; // File doesn't exist already, just use it!
709 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
710 // mktemp or our own implementation.
711 char *FNBuffer = (char*) alloca(path.size()+8);
712 path.copy(FNBuffer,path.size());
713 strcpy(FNBuffer+path.size(), "-XXXXXX");
715 #if defined(HAVE_MKSTEMP)
717 if ((TempFD = mkstemp(FNBuffer)) == -1)
718 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
720 // We don't need to hold the temp file descriptor... we will trust that no one
721 // will overwrite/delete the file before we can open it again.
726 #elif defined(HAVE_MKTEMP)
727 // If we don't have mkstemp, use the old and obsolete mktemp function.
728 if (mktemp(FNBuffer) == 0)
729 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
734 // Okay, looks like we have to do it all by our lonesome.
735 static unsigned FCounter = 0;
736 unsigned offset = path.size() + 1;
737 while ( FCounter < 999999 && exists()) {
738 sprintf(FNBuffer+offset,"%06u",++FCounter);
741 if (FCounter > 999999)
742 return MakeErrMsg(ErrMsg,
743 path + ": can't make unique filename: too many files");
748 const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
749 int Flags = MAP_PRIVATE;
753 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
754 if (BasePtr == MAP_FAILED)
759 void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
760 ::munmap(BasePtr, FileSize);
763 } // end llvm namespace