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"
27 #ifdef HAVE_SYS_MMAN_H
30 #ifdef HAVE_SYS_STAT_H
41 # define NAMLEN(dirent) strlen((dirent)->d_name)
43 # define dirent direct
44 # define NAMLEN(dirent) (dirent)->d_namlen
46 # include <sys/ndir.h>
60 // Put in a hack for Cygwin which falsely reports that the mkdtemp function
61 // is available when it is not.
67 inline bool lastIsSlash(const std::string& path) {
68 return !path.empty() && path[path.length() - 1] == '/';
76 extern const char sys::PathSeparator = ':';
78 Path::Path(const std::string& p)
81 Path::Path(const char *StrStart, unsigned StrLen)
82 : path(StrStart, StrLen) {}
85 Path::isValid() const {
86 // Check some obvious things
89 else if (path.length() >= MAXPATHLEN)
92 // Check that the characters are ascii chars
93 size_t len = path.length();
95 while (i < len && isascii(path[i]))
101 Path::isAbsolute() const {
104 return path[0] == '/';
107 Path::GetRootDirectory() {
114 Path::GetTemporaryDirectory(std::string* ErrMsg ) {
115 #if defined(HAVE_MKDTEMP)
116 // The best way is with mkdtemp but that's not available on many systems,
117 // Linux and FreeBSD have it. Others probably won't.
118 char pathname[MAXPATHLEN];
119 strcpy(pathname,"/tmp/llvm_XXXXXX");
120 if (0 == mkdtemp(pathname)) {
122 std::string(pathname) + ": can't create temporary directory");
126 result.set(pathname);
127 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
129 #elif defined(HAVE_MKSTEMP)
130 // If no mkdtemp is available, mkstemp can be used to create a temporary file
131 // which is then removed and created as a directory. We prefer this over
132 // mktemp because of mktemp's inherent security and threading risks. We still
133 // have a slight race condition from the time the temporary file is created to
134 // the time it is re-created as a directoy.
135 char pathname[MAXPATHLEN];
136 strcpy(pathname, "/tmp/llvm_XXXXXX");
138 if (-1 == (fd = mkstemp(pathname))) {
140 std::string(pathname) + ": can't create temporary directory");
144 ::unlink(pathname); // start race condition, ignore errors
145 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
147 std::string(pathname) + ": can't create temporary directory");
151 result.set(pathname);
152 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
154 #elif defined(HAVE_MKTEMP)
155 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
156 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
157 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
158 // the XXXXXX with the pid of the process and a letter. That leads to only
159 // twenty six temporary files that can be generated.
160 char pathname[MAXPATHLEN];
161 strcpy(pathname, "/tmp/llvm_XXXXXX");
162 char *TmpName = ::mktemp(pathname);
165 std::string(TmpName) + ": can't create unique directory name");
168 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
170 std::string(TmpName) + ": can't create temporary directory");
175 assert(result.isValid() && "mktemp didn't create a valid pathname!");
178 // This is the worst case implementation. tempnam(3) leaks memory unless its
179 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
180 // issues. The mktemp(3) function doesn't have enough variability in the
181 // temporary name generated. So, we provide our own implementation that
182 // increments an integer from a random number seeded by the current time. This
183 // should be sufficiently unique that we don't have many collisions between
184 // processes. Generally LLVM processes don't run very long and don't use very
185 // many temporary files so this shouldn't be a big issue for LLVM.
186 static time_t num = ::time(0);
187 char pathname[MAXPATHLEN];
190 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
191 } while ( 0 == access(pathname, F_OK ) );
192 if (-1 == ::mkdir(pathname, S_IRWXU)) {
194 std::string(pathname) + ": can't create temporary directory");
198 result.set(pathname);
199 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
205 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
206 #ifdef LTDL_SHLIBPATH_VAR
207 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
209 getPathList(env_var,Paths);
212 // FIXME: Should this look at LD_LIBRARY_PATH too?
213 Paths.push_back(sys::Path("/usr/local/lib/"));
214 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
215 Paths.push_back(sys::Path("/usr/lib/"));
216 Paths.push_back(sys::Path("/lib/"));
220 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
221 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
223 getPathList(env_var,Paths);
228 if (tmpPath.set(LLVM_LIBDIR))
229 if (tmpPath.canRead())
230 Paths.push_back(tmpPath);
233 GetSystemLibraryPaths(Paths);
237 Path::GetLLVMDefaultConfigDir() {
238 return Path("/etc/llvm/");
242 Path::GetUserHomeDirectory() {
243 const char* home = getenv("HOME");
246 if (result.set(home))
249 return GetRootDirectory();
253 Path::GetCurrentDirectory() {
254 char pathname[MAXPATHLEN];
255 if (!getcwd(pathname,MAXPATHLEN)) {
256 assert (false && "Could not query current working directory.");
260 return Path(pathname);
263 /// GetMainExecutable - Return the path to the main executable, given the
264 /// value of argv[0] from program startup.
265 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
266 #if defined(__linux__) || defined(__CYGWIN__)
267 char exe_path[MAXPATHLEN];
268 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
269 if (len > 0 && len < MAXPATHLEN - 1) {
270 exe_path[len] = '\0';
271 return Path(std::string(exe_path));
273 #elif defined(HAVE_DLFCN_H)
274 // Use dladdr to get executable path if available.
276 int err = dladdr(MainAddr, &DLInfo);
278 return Path(std::string(DLInfo.dli_fname));
284 std::string Path::getDirname() const {
285 return getDirnameCharSep(path, '/');
289 Path::getBasename() const {
290 // Find the last slash
291 std::string::size_type slash = path.rfind('/');
292 if (slash == std::string::npos)
297 std::string::size_type dot = path.rfind('.');
298 if (dot == std::string::npos || dot < slash)
299 return path.substr(slash);
301 return path.substr(slash, dot - slash);
305 Path::getSuffix() const {
306 // Find the last slash
307 std::string::size_type slash = path.rfind('/');
308 if (slash == std::string::npos)
313 std::string::size_type dot = path.rfind('.');
314 if (dot == std::string::npos || dot < slash)
315 return std::string();
317 return path.substr(dot + 1);
320 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
321 assert(len < 1024 && "Request for magic string too long");
322 char* buf = (char*) alloca(1 + len);
323 int fd = ::open(path.c_str(), O_RDONLY);
326 ssize_t bytes_read = ::read(fd, buf, len);
328 if (ssize_t(len) != bytes_read) {
332 Magic.assign(buf,len);
337 Path::exists() const {
338 return 0 == access(path.c_str(), F_OK );
342 Path::isDirectory() const {
344 if (0 != stat(path.c_str(), &buf))
346 return buf.st_mode & S_IFDIR ? true : false;
350 Path::canRead() const {
351 return 0 == access(path.c_str(), F_OK | R_OK );
355 Path::canWrite() const {
356 return 0 == access(path.c_str(), F_OK | W_OK );
360 Path::canExecute() const {
361 if (0 != access(path.c_str(), R_OK | X_OK ))
364 if (0 != stat(path.c_str(), &buf))
366 if (!S_ISREG(buf.st_mode))
372 Path::getLast() const {
373 // Find the last slash
374 size_t pos = path.rfind('/');
376 // Handle the corner cases
377 if (pos == std::string::npos)
380 // If the last character is a slash
381 if (pos == path.length()-1) {
382 // Find the second to last slash
383 size_t pos2 = path.rfind('/', pos-1);
384 if (pos2 == std::string::npos)
385 return path.substr(0,pos);
387 return path.substr(pos2+1,pos-pos2-1);
389 // Return everything after the last slash
390 return path.substr(pos+1);
394 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
395 if (!fsIsValid || update) {
397 if (0 != stat(path.c_str(), &buf)) {
398 MakeErrMsg(ErrStr, path + ": can't get status of file");
401 status.fileSize = buf.st_size;
402 status.modTime.fromEpochTime(buf.st_mtime);
403 status.mode = buf.st_mode;
404 status.user = buf.st_uid;
405 status.group = buf.st_gid;
406 status.uniqueID = uint64_t(buf.st_ino);
407 status.isDir = S_ISDIR(buf.st_mode);
408 status.isFile = S_ISREG(buf.st_mode);
414 static bool AddPermissionBits(const Path &File, int bits) {
415 // Get the umask value from the operating system. We want to use it
416 // when changing the file's permissions. Since calling umask() sets
417 // the umask and returns its old value, we must call it a second
418 // time to reset it to the user's preference.
419 int mask = umask(0777); // The arg. to umask is arbitrary.
420 umask(mask); // Restore the umask.
422 // Get the file's current mode.
424 if (0 != stat(File.toString().c_str(), &buf))
426 // Change the file to have whichever permissions bits from 'bits'
427 // that the umask would not disable.
428 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
433 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
434 if (!AddPermissionBits(*this, 0444))
435 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
439 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
440 if (!AddPermissionBits(*this, 0222))
441 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
445 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
446 if (!AddPermissionBits(*this, 0111))
447 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
452 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
453 DIR* direntries = ::opendir(path.c_str());
455 return MakeErrMsg(ErrMsg, path + ": can't open directory");
457 std::string dirPath = path;
458 if (!lastIsSlash(dirPath))
462 struct dirent* de = ::readdir(direntries);
463 for ( ; de != 0; de = ::readdir(direntries)) {
464 if (de->d_name[0] != '.') {
465 Path aPath(dirPath + (const char*)de->d_name);
467 if (0 != lstat(aPath.path.c_str(), &st)) {
468 if (S_ISLNK(st.st_mode))
469 continue; // dangling symlink -- ignore
470 return MakeErrMsg(ErrMsg,
471 aPath.path + ": can't determine file object type");
473 result.insert(aPath);
477 closedir(direntries);
482 Path::set(const std::string& a_path) {
485 std::string save(path);
495 Path::appendComponent(const std::string& name) {
498 std::string save(path);
499 if (!lastIsSlash(path))
510 Path::eraseComponent() {
511 size_t slashpos = path.rfind('/',path.size());
512 if (slashpos == 0 || slashpos == std::string::npos) {
516 if (slashpos == path.size() - 1)
517 slashpos = path.rfind('/',slashpos-1);
518 if (slashpos == std::string::npos) {
522 path.erase(slashpos);
527 Path::appendSuffix(const std::string& suffix) {
528 std::string save(path);
539 Path::eraseSuffix() {
540 std::string save = path;
541 size_t dotpos = path.rfind('.',path.size());
542 size_t slashpos = path.rfind('/',path.size());
543 if (dotpos != std::string::npos) {
544 if (slashpos == std::string::npos || dotpos > slashpos+1) {
545 path.erase(dotpos, path.size()-dotpos);
554 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
556 if (access(beg, F_OK | R_OK | W_OK) == 0)
559 if (create_parents) {
563 for (; c != beg; --c)
566 // Recurse to handling the parent directory.
568 bool x = createDirectoryHelper(beg, c, create_parents);
571 // Return if we encountered an error.
579 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
583 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
584 // Get a writeable copy of the path name
585 char pathname[MAXPATHLEN];
586 path.copy(pathname,MAXPATHLEN);
588 // Null-terminate the last component
589 size_t lastchar = path.length() - 1 ;
591 if (pathname[lastchar] != '/')
594 pathname[lastchar] = 0;
596 if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
597 return MakeErrMsg(ErrMsg,
598 std::string(pathname) + ": can't create directory");
604 Path::createFileOnDisk(std::string* ErrMsg) {
606 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
608 return MakeErrMsg(ErrMsg, path + ": can't create file");
614 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
615 // Make this into a unique file name
616 if (makeUnique( reuse_current, ErrMsg ))
620 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
622 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
628 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
629 // Get the status so we can determin if its a file or directory
631 if (0 != stat(path.c_str(), &buf)) {
632 MakeErrMsg(ErrStr, path + ": can't get status of file");
636 // Note: this check catches strange situations. In all cases, LLVM should
637 // only be involved in the creation and deletion of regular files. This
638 // check ensures that what we're trying to erase is a regular file. It
639 // effectively prevents LLVM from erasing things like /dev/null, any block
640 // special file, or other things that aren't "regular" files.
641 if (S_ISREG(buf.st_mode)) {
642 if (unlink(path.c_str()) != 0)
643 return MakeErrMsg(ErrStr, path + ": can't destroy file");
647 if (!S_ISDIR(buf.st_mode)) {
648 if (ErrStr) *ErrStr = "not a file or directory";
652 if (remove_contents) {
653 // Recursively descend the directory to remove its contents.
654 std::string cmd = "/bin/rm -rf " + path;
659 // Otherwise, try to just remove the one directory.
660 char pathname[MAXPATHLEN];
661 path.copy(pathname, MAXPATHLEN);
662 size_t lastchar = path.length() - 1;
663 if (pathname[lastchar] == '/')
664 pathname[lastchar] = 0;
666 pathname[lastchar+1] = 0;
668 if (rmdir(pathname) != 0)
669 return MakeErrMsg(ErrStr,
670 std::string(pathname) + ": can't erase directory");
675 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
676 if (0 != ::rename(path.c_str(), newName.c_str()))
677 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
678 newName.toString() + "' ");
683 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
685 utb.actime = si.modTime.toPosixTime();
686 utb.modtime = utb.actime;
687 if (0 != ::utime(path.c_str(),&utb))
688 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
689 if (0 != ::chmod(path.c_str(),si.mode))
690 return MakeErrMsg(ErrStr, path + ": can't set mode");
695 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
698 inFile = ::open(Src.c_str(), O_RDONLY);
700 return MakeErrMsg(ErrMsg, Src.toString() +
701 ": can't open source file to copy");
703 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
706 return MakeErrMsg(ErrMsg, Dest.toString() +
707 ": can't create destination file for copy");
710 char Buffer[16*1024];
711 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
713 if (errno != EINTR && errno != EAGAIN) {
716 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file: ");
719 char *BufPtr = Buffer;
721 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
722 if (AmtWritten == -1) {
723 if (errno != EINTR && errno != EAGAIN) {
726 return MakeErrMsg(ErrMsg, Dest.toString() +
727 ": can't write destination file: ");
731 BufPtr += AmtWritten;
742 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
743 if (reuse_current && !exists())
744 return false; // File doesn't exist already, just use it!
746 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
747 // mktemp or our own implementation.
748 char *FNBuffer = (char*) alloca(path.size()+8);
750 std::string dirPath = getDirname();
751 strcpy(FNBuffer, dirPath.c_str());
752 strcpy(FNBuffer+dirPath.size(), "XXXXXX");
754 path.copy(FNBuffer,path.size());
755 strcpy(FNBuffer+path.size(), "-XXXXXX");
758 #if defined(HAVE_MKSTEMP)
760 if ((TempFD = mkstemp(FNBuffer)) == -1)
761 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
763 // We don't need to hold the temp file descriptor... we will trust that no one
764 // will overwrite/delete the file before we can open it again.
769 #elif defined(HAVE_MKTEMP)
770 // If we don't have mkstemp, use the old and obsolete mktemp function.
771 if (mktemp(FNBuffer) == 0)
772 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
777 // Okay, looks like we have to do it all by our lonesome.
778 static unsigned FCounter = 0;
779 unsigned offset = path.size() + 1;
780 while ( FCounter < 999999 && exists()) {
781 sprintf(FNBuffer+offset,"%06u",++FCounter);
784 if (FCounter > 999999)
785 return MakeErrMsg(ErrMsg,
786 path + ": can't make unique filename: too many files");
791 const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
792 int Flags = MAP_PRIVATE;
796 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
797 if (BasePtr == MAP_FAILED)
799 return (const char*)BasePtr;
802 void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
803 ::munmap((void*)BasePtr, FileSize);
806 } // end llvm namespace