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::operator=(const std::string &that) {
91 Path::isValid() const {
92 // Check some obvious things
95 else if (path.length() >= MAXPATHLEN)
98 // Check that the characters are ascii chars
99 size_t len = path.length();
101 while (i < len && isascii(path[i]))
107 Path::isAbsolute(const char *NameStart, unsigned NameLen) {
111 return NameStart[0] == '/';
115 Path::isAbsolute() const {
118 return path[0] == '/';
121 Path::GetRootDirectory() {
128 Path::GetTemporaryDirectory(std::string *ErrMsg) {
129 #if defined(HAVE_MKDTEMP)
130 // The best way is with mkdtemp but that's not available on many systems,
131 // Linux and FreeBSD have it. Others probably won't.
132 char pathname[MAXPATHLEN];
133 strcpy(pathname,"/tmp/llvm_XXXXXX");
134 if (0 == mkdtemp(pathname)) {
136 std::string(pathname) + ": can't create temporary directory");
140 result.set(pathname);
141 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
143 #elif defined(HAVE_MKSTEMP)
144 // If no mkdtemp is available, mkstemp can be used to create a temporary file
145 // which is then removed and created as a directory. We prefer this over
146 // mktemp because of mktemp's inherent security and threading risks. We still
147 // have a slight race condition from the time the temporary file is created to
148 // the time it is re-created as a directoy.
149 char pathname[MAXPATHLEN];
150 strcpy(pathname, "/tmp/llvm_XXXXXX");
152 if (-1 == (fd = mkstemp(pathname))) {
154 std::string(pathname) + ": can't create temporary directory");
158 ::unlink(pathname); // start race condition, ignore errors
159 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
161 std::string(pathname) + ": can't create temporary directory");
165 result.set(pathname);
166 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
168 #elif defined(HAVE_MKTEMP)
169 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
170 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
171 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
172 // the XXXXXX with the pid of the process and a letter. That leads to only
173 // twenty six temporary files that can be generated.
174 char pathname[MAXPATHLEN];
175 strcpy(pathname, "/tmp/llvm_XXXXXX");
176 char *TmpName = ::mktemp(pathname);
179 std::string(TmpName) + ": can't create unique directory name");
182 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
184 std::string(TmpName) + ": can't create temporary directory");
189 assert(result.isValid() && "mktemp didn't create a valid pathname!");
192 // This is the worst case implementation. tempnam(3) leaks memory unless its
193 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
194 // issues. The mktemp(3) function doesn't have enough variability in the
195 // temporary name generated. So, we provide our own implementation that
196 // increments an integer from a random number seeded by the current time. This
197 // should be sufficiently unique that we don't have many collisions between
198 // processes. Generally LLVM processes don't run very long and don't use very
199 // many temporary files so this shouldn't be a big issue for LLVM.
200 static time_t num = ::time(0);
201 char pathname[MAXPATHLEN];
204 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
205 } while ( 0 == access(pathname, F_OK ) );
206 if (-1 == ::mkdir(pathname, S_IRWXU)) {
208 std::string(pathname) + ": can't create temporary directory");
212 result.set(pathname);
213 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
219 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
220 #ifdef LTDL_SHLIBPATH_VAR
221 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
223 getPathList(env_var,Paths);
226 // FIXME: Should this look at LD_LIBRARY_PATH too?
227 Paths.push_back(sys::Path("/usr/local/lib/"));
228 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
229 Paths.push_back(sys::Path("/usr/lib/"));
230 Paths.push_back(sys::Path("/lib/"));
234 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
235 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
237 getPathList(env_var,Paths);
242 if (tmpPath.set(LLVM_LIBDIR))
243 if (tmpPath.canRead())
244 Paths.push_back(tmpPath);
247 GetSystemLibraryPaths(Paths);
251 Path::GetLLVMDefaultConfigDir() {
252 return Path("/etc/llvm/");
256 Path::GetUserHomeDirectory() {
257 const char* home = getenv("HOME");
260 if (result.set(home))
263 return GetRootDirectory();
267 Path::GetCurrentDirectory() {
268 char pathname[MAXPATHLEN];
269 if (!getcwd(pathname,MAXPATHLEN)) {
270 assert (false && "Could not query current working directory.");
274 return Path(pathname);
279 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
280 const char *dir, const char *bin)
284 snprintf(buf, PATH_MAX, "%s//%s", dir, bin);
285 if (realpath(buf, ret) == NULL)
287 if (stat(buf, &sb) != 0)
294 getprogpath(char ret[PATH_MAX], const char *bin)
296 char *pv, *s, *t, buf[PATH_MAX];
298 /* First approach: absolute path. */
300 if (test_dir(buf, ret, "/", bin) == 0)
305 /* Second approach: relative path. */
306 if (strchr(bin, '/') != NULL) {
307 if (getcwd(buf, PATH_MAX) == NULL)
309 if (test_dir(buf, ret, buf, bin) == 0)
314 /* Third approach: $PATH */
315 if ((pv = getenv("PATH")) == NULL)
320 while ((t = strsep(&s, ":")) != NULL) {
321 if (test_dir(buf, ret, t, bin) == 0) {
331 /// GetMainExecutable - Return the path to the main executable, given the
332 /// value of argv[0] from program startup.
333 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
334 #if defined(__FreeBSD__)
335 char exe_path[PATH_MAX];
337 if (getprogpath(exe_path, argv0) != NULL)
338 return Path(std::string(exe_path));
339 #elif defined(__linux__) || defined(__CYGWIN__)
340 char exe_path[MAXPATHLEN];
341 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
342 if (len > 0 && len < MAXPATHLEN - 1) {
343 exe_path[len] = '\0';
344 return Path(std::string(exe_path));
346 #elif defined(HAVE_DLFCN_H)
347 // Use dladdr to get executable path if available.
349 int err = dladdr(MainAddr, &DLInfo);
353 // If the filename is a symlink, we need to resolve and return the location of
354 // the actual executable.
355 char link_path[MAXPATHLEN];
356 return Path(std::string(realpath(DLInfo.dli_fname, link_path)));
362 std::string Path::getDirname() const {
363 return getDirnameCharSep(path, '/');
367 Path::getBasename() const {
368 // Find the last slash
369 std::string::size_type slash = path.rfind('/');
370 if (slash == std::string::npos)
375 std::string::size_type dot = path.rfind('.');
376 if (dot == std::string::npos || dot < slash)
377 return path.substr(slash);
379 return path.substr(slash, dot - slash);
383 Path::getSuffix() const {
384 // Find the last slash
385 std::string::size_type slash = path.rfind('/');
386 if (slash == std::string::npos)
391 std::string::size_type dot = path.rfind('.');
392 if (dot == std::string::npos || dot < slash)
393 return std::string();
395 return path.substr(dot + 1);
398 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
399 assert(len < 1024 && "Request for magic string too long");
400 char* buf = (char*) alloca(1 + len);
401 int fd = ::open(path.c_str(), O_RDONLY);
404 ssize_t bytes_read = ::read(fd, buf, len);
406 if (ssize_t(len) != bytes_read) {
410 Magic.assign(buf,len);
415 Path::exists() const {
416 return 0 == access(path.c_str(), F_OK );
420 Path::isDirectory() const {
422 if (0 != stat(path.c_str(), &buf))
424 return buf.st_mode & S_IFDIR ? true : false;
428 Path::canRead() const {
429 return 0 == access(path.c_str(), F_OK | R_OK );
433 Path::canWrite() const {
434 return 0 == access(path.c_str(), F_OK | W_OK );
438 Path::canExecute() const {
439 if (0 != access(path.c_str(), R_OK | X_OK ))
442 if (0 != stat(path.c_str(), &buf))
444 if (!S_ISREG(buf.st_mode))
450 Path::getLast() const {
451 // Find the last slash
452 size_t pos = path.rfind('/');
454 // Handle the corner cases
455 if (pos == std::string::npos)
458 // If the last character is a slash
459 if (pos == path.length()-1) {
460 // Find the second to last slash
461 size_t pos2 = path.rfind('/', pos-1);
462 if (pos2 == std::string::npos)
463 return path.substr(0,pos);
465 return path.substr(pos2+1,pos-pos2-1);
467 // Return everything after the last slash
468 return path.substr(pos+1);
472 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
473 if (!fsIsValid || update) {
475 if (0 != stat(path.c_str(), &buf)) {
476 MakeErrMsg(ErrStr, path + ": can't get status of file");
479 status.fileSize = buf.st_size;
480 status.modTime.fromEpochTime(buf.st_mtime);
481 status.mode = buf.st_mode;
482 status.user = buf.st_uid;
483 status.group = buf.st_gid;
484 status.uniqueID = uint64_t(buf.st_ino);
485 status.isDir = S_ISDIR(buf.st_mode);
486 status.isFile = S_ISREG(buf.st_mode);
492 static bool AddPermissionBits(const Path &File, int bits) {
493 // Get the umask value from the operating system. We want to use it
494 // when changing the file's permissions. Since calling umask() sets
495 // the umask and returns its old value, we must call it a second
496 // time to reset it to the user's preference.
497 int mask = umask(0777); // The arg. to umask is arbitrary.
498 umask(mask); // Restore the umask.
500 // Get the file's current mode.
502 if (0 != stat(File.toString().c_str(), &buf))
504 // Change the file to have whichever permissions bits from 'bits'
505 // that the umask would not disable.
506 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
511 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
512 if (!AddPermissionBits(*this, 0444))
513 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
517 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
518 if (!AddPermissionBits(*this, 0222))
519 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
523 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
524 if (!AddPermissionBits(*this, 0111))
525 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
530 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
531 DIR* direntries = ::opendir(path.c_str());
533 return MakeErrMsg(ErrMsg, path + ": can't open directory");
535 std::string dirPath = path;
536 if (!lastIsSlash(dirPath))
540 struct dirent* de = ::readdir(direntries);
541 for ( ; de != 0; de = ::readdir(direntries)) {
542 if (de->d_name[0] != '.') {
543 Path aPath(dirPath + (const char*)de->d_name);
545 if (0 != lstat(aPath.path.c_str(), &st)) {
546 if (S_ISLNK(st.st_mode))
547 continue; // dangling symlink -- ignore
548 return MakeErrMsg(ErrMsg,
549 aPath.path + ": can't determine file object type");
551 result.insert(aPath);
555 closedir(direntries);
560 Path::set(const std::string& a_path) {
563 std::string save(path);
573 Path::appendComponent(const std::string& name) {
576 std::string save(path);
577 if (!lastIsSlash(path))
588 Path::eraseComponent() {
589 size_t slashpos = path.rfind('/',path.size());
590 if (slashpos == 0 || slashpos == std::string::npos) {
594 if (slashpos == path.size() - 1)
595 slashpos = path.rfind('/',slashpos-1);
596 if (slashpos == std::string::npos) {
600 path.erase(slashpos);
605 Path::appendSuffix(const std::string& suffix) {
606 std::string save(path);
617 Path::eraseSuffix() {
618 std::string save = path;
619 size_t dotpos = path.rfind('.',path.size());
620 size_t slashpos = path.rfind('/',path.size());
621 if (dotpos != std::string::npos) {
622 if (slashpos == std::string::npos || dotpos > slashpos+1) {
623 path.erase(dotpos, path.size()-dotpos);
632 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
634 if (access(beg, F_OK | R_OK | W_OK) == 0)
637 if (create_parents) {
641 for (; c != beg; --c)
644 // Recurse to handling the parent directory.
646 bool x = createDirectoryHelper(beg, c, create_parents);
649 // Return if we encountered an error.
657 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
661 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
662 // Get a writeable copy of the path name
663 char pathname[MAXPATHLEN];
664 path.copy(pathname,MAXPATHLEN);
666 // Null-terminate the last component
667 size_t lastchar = path.length() - 1 ;
669 if (pathname[lastchar] != '/')
672 pathname[lastchar] = 0;
674 if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
675 return MakeErrMsg(ErrMsg,
676 std::string(pathname) + ": can't create directory");
682 Path::createFileOnDisk(std::string* ErrMsg) {
684 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
686 return MakeErrMsg(ErrMsg, path + ": can't create file");
692 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
693 // Make this into a unique file name
694 if (makeUnique( reuse_current, ErrMsg ))
698 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
700 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
706 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
707 // Get the status so we can determin if its a file or directory
709 if (0 != stat(path.c_str(), &buf)) {
710 MakeErrMsg(ErrStr, path + ": can't get status of file");
714 // Note: this check catches strange situations. In all cases, LLVM should
715 // only be involved in the creation and deletion of regular files. This
716 // check ensures that what we're trying to erase is a regular file. It
717 // effectively prevents LLVM from erasing things like /dev/null, any block
718 // special file, or other things that aren't "regular" files.
719 if (S_ISREG(buf.st_mode)) {
720 if (unlink(path.c_str()) != 0)
721 return MakeErrMsg(ErrStr, path + ": can't destroy file");
725 if (!S_ISDIR(buf.st_mode)) {
726 if (ErrStr) *ErrStr = "not a file or directory";
730 if (remove_contents) {
731 // Recursively descend the directory to remove its contents.
732 std::string cmd = "/bin/rm -rf " + path;
733 if (system(cmd.c_str()) != 0) {
734 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
740 // Otherwise, try to just remove the one directory.
741 char pathname[MAXPATHLEN];
742 path.copy(pathname, MAXPATHLEN);
743 size_t lastchar = path.length() - 1;
744 if (pathname[lastchar] == '/')
745 pathname[lastchar] = 0;
747 pathname[lastchar+1] = 0;
749 if (rmdir(pathname) != 0)
750 return MakeErrMsg(ErrStr,
751 std::string(pathname) + ": can't erase directory");
756 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
757 if (0 != ::rename(path.c_str(), newName.c_str()))
758 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
759 newName.toString() + "'");
764 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
766 utb.actime = si.modTime.toPosixTime();
767 utb.modtime = utb.actime;
768 if (0 != ::utime(path.c_str(),&utb))
769 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
770 if (0 != ::chmod(path.c_str(),si.mode))
771 return MakeErrMsg(ErrStr, path + ": can't set mode");
776 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
779 inFile = ::open(Src.c_str(), O_RDONLY);
781 return MakeErrMsg(ErrMsg, Src.toString() +
782 ": can't open source file to copy");
784 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
787 return MakeErrMsg(ErrMsg, Dest.toString() +
788 ": can't create destination file for copy");
791 char Buffer[16*1024];
792 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
794 if (errno != EINTR && errno != EAGAIN) {
797 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file");
800 char *BufPtr = Buffer;
802 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
803 if (AmtWritten == -1) {
804 if (errno != EINTR && errno != EAGAIN) {
807 return MakeErrMsg(ErrMsg, Dest.toString() +
808 ": can't write destination file");
812 BufPtr += AmtWritten;
823 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
824 if (reuse_current && !exists())
825 return false; // File doesn't exist already, just use it!
827 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
828 // mktemp or our own implementation.
829 char *FNBuffer = (char*) alloca(path.size()+8);
830 path.copy(FNBuffer,path.size());
832 strcpy(FNBuffer+path.size(), "/XXXXXX");
834 strcpy(FNBuffer+path.size(), "-XXXXXX");
836 #if defined(HAVE_MKSTEMP)
838 if ((TempFD = mkstemp(FNBuffer)) == -1)
839 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
841 // We don't need to hold the temp file descriptor... we will trust that no one
842 // will overwrite/delete the file before we can open it again.
847 #elif defined(HAVE_MKTEMP)
848 // If we don't have mkstemp, use the old and obsolete mktemp function.
849 if (mktemp(FNBuffer) == 0)
850 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
855 // Okay, looks like we have to do it all by our lonesome.
856 static unsigned FCounter = 0;
857 unsigned offset = path.size() + 1;
858 while ( FCounter < 999999 && exists()) {
859 sprintf(FNBuffer+offset,"%06u",++FCounter);
862 if (FCounter > 999999)
863 return MakeErrMsg(ErrMsg,
864 path + ": can't make unique filename: too many files");
869 const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
870 int Flags = MAP_PRIVATE;
874 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
875 if (BasePtr == MAP_FAILED)
877 return (const char*)BasePtr;
880 void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
881 ::munmap((void*)BasePtr, FileSize);
884 } // end llvm namespace