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 return path.length() < MAXPATHLEN;
99 Path::isAbsolute(const char *NameStart, unsigned NameLen) {
103 return NameStart[0] == '/';
107 Path::isAbsolute() const {
110 return path[0] == '/';
113 void Path::makeAbsolute() {
117 Path CWD = Path::GetCurrentDirectory();
118 assert(CWD.isAbsolute() && "GetCurrentDirectory returned relative path!");
120 CWD.appendComponent(path);
122 path = CWD.toString();
126 Path::GetRootDirectory() {
133 Path::GetTemporaryDirectory(std::string *ErrMsg) {
134 #if defined(HAVE_MKDTEMP)
135 // The best way is with mkdtemp but that's not available on many systems,
136 // Linux and FreeBSD have it. Others probably won't.
137 char pathname[MAXPATHLEN];
138 strcpy(pathname,"/tmp/llvm_XXXXXX");
139 if (0 == mkdtemp(pathname)) {
141 std::string(pathname) + ": can't create temporary directory");
145 result.set(pathname);
146 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
148 #elif defined(HAVE_MKSTEMP)
149 // If no mkdtemp is available, mkstemp can be used to create a temporary file
150 // which is then removed and created as a directory. We prefer this over
151 // mktemp because of mktemp's inherent security and threading risks. We still
152 // have a slight race condition from the time the temporary file is created to
153 // the time it is re-created as a directoy.
154 char pathname[MAXPATHLEN];
155 strcpy(pathname, "/tmp/llvm_XXXXXX");
157 if (-1 == (fd = mkstemp(pathname))) {
159 std::string(pathname) + ": can't create temporary directory");
163 ::unlink(pathname); // start race condition, ignore errors
164 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
166 std::string(pathname) + ": can't create temporary directory");
170 result.set(pathname);
171 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
173 #elif defined(HAVE_MKTEMP)
174 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
175 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
176 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
177 // the XXXXXX with the pid of the process and a letter. That leads to only
178 // twenty six temporary files that can be generated.
179 char pathname[MAXPATHLEN];
180 strcpy(pathname, "/tmp/llvm_XXXXXX");
181 char *TmpName = ::mktemp(pathname);
184 std::string(TmpName) + ": can't create unique directory name");
187 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
189 std::string(TmpName) + ": can't create temporary directory");
194 assert(result.isValid() && "mktemp didn't create a valid pathname!");
197 // This is the worst case implementation. tempnam(3) leaks memory unless its
198 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
199 // issues. The mktemp(3) function doesn't have enough variability in the
200 // temporary name generated. So, we provide our own implementation that
201 // increments an integer from a random number seeded by the current time. This
202 // should be sufficiently unique that we don't have many collisions between
203 // processes. Generally LLVM processes don't run very long and don't use very
204 // many temporary files so this shouldn't be a big issue for LLVM.
205 static time_t num = ::time(0);
206 char pathname[MAXPATHLEN];
209 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
210 } while ( 0 == access(pathname, F_OK ) );
211 if (-1 == ::mkdir(pathname, S_IRWXU)) {
213 std::string(pathname) + ": can't create temporary directory");
217 result.set(pathname);
218 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
224 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
225 #ifdef LTDL_SHLIBPATH_VAR
226 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
228 getPathList(env_var,Paths);
231 // FIXME: Should this look at LD_LIBRARY_PATH too?
232 Paths.push_back(sys::Path("/usr/local/lib/"));
233 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
234 Paths.push_back(sys::Path("/usr/lib/"));
235 Paths.push_back(sys::Path("/lib/"));
239 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
240 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
242 getPathList(env_var,Paths);
247 if (tmpPath.set(LLVM_LIBDIR))
248 if (tmpPath.canRead())
249 Paths.push_back(tmpPath);
252 GetSystemLibraryPaths(Paths);
256 Path::GetLLVMDefaultConfigDir() {
257 return Path("/etc/llvm/");
261 Path::GetUserHomeDirectory() {
262 const char* home = getenv("HOME");
265 if (result.set(home))
268 return GetRootDirectory();
272 Path::GetCurrentDirectory() {
273 char pathname[MAXPATHLEN];
274 if (!getcwd(pathname,MAXPATHLEN)) {
275 assert (false && "Could not query current working directory.");
279 return Path(pathname);
284 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
285 const char *dir, const char *bin)
289 snprintf(buf, PATH_MAX, "%s//%s", dir, bin);
290 if (realpath(buf, ret) == NULL)
292 if (stat(buf, &sb) != 0)
299 getprogpath(char ret[PATH_MAX], const char *bin)
301 char *pv, *s, *t, buf[PATH_MAX];
303 /* First approach: absolute path. */
305 if (test_dir(buf, ret, "/", bin) == 0)
310 /* Second approach: relative path. */
311 if (strchr(bin, '/') != NULL) {
312 if (getcwd(buf, PATH_MAX) == NULL)
314 if (test_dir(buf, ret, buf, bin) == 0)
319 /* Third approach: $PATH */
320 if ((pv = getenv("PATH")) == NULL)
325 while ((t = strsep(&s, ":")) != NULL) {
326 if (test_dir(buf, ret, t, bin) == 0) {
336 /// GetMainExecutable - Return the path to the main executable, given the
337 /// value of argv[0] from program startup.
338 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
339 #if defined(__FreeBSD__)
340 char exe_path[PATH_MAX];
342 if (getprogpath(exe_path, argv0) != NULL)
343 return Path(std::string(exe_path));
344 #elif defined(__linux__) || defined(__CYGWIN__)
345 char exe_path[MAXPATHLEN];
346 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
347 if (len > 0 && len < MAXPATHLEN - 1) {
348 exe_path[len] = '\0';
349 return Path(std::string(exe_path));
351 #elif defined(HAVE_DLFCN_H)
352 // Use dladdr to get executable path if available.
354 int err = dladdr(MainAddr, &DLInfo);
358 // If the filename is a symlink, we need to resolve and return the location of
359 // the actual executable.
360 char link_path[MAXPATHLEN];
361 return Path(std::string(realpath(DLInfo.dli_fname, link_path)));
367 std::string Path::getDirname() const {
368 return getDirnameCharSep(path, '/');
372 Path::getBasename() const {
373 // Find the last slash
374 std::string::size_type slash = path.rfind('/');
375 if (slash == std::string::npos)
380 std::string::size_type dot = path.rfind('.');
381 if (dot == std::string::npos || dot < slash)
382 return path.substr(slash);
384 return path.substr(slash, dot - slash);
388 Path::getSuffix() const {
389 // Find the last slash
390 std::string::size_type slash = path.rfind('/');
391 if (slash == std::string::npos)
396 std::string::size_type dot = path.rfind('.');
397 if (dot == std::string::npos || dot < slash)
398 return std::string();
400 return path.substr(dot + 1);
403 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
404 assert(len < 1024 && "Request for magic string too long");
405 char* buf = (char*) alloca(1 + len);
406 int fd = ::open(path.c_str(), O_RDONLY);
409 ssize_t bytes_read = ::read(fd, buf, len);
411 if (ssize_t(len) != bytes_read) {
415 Magic.assign(buf,len);
420 Path::exists() const {
421 return 0 == access(path.c_str(), F_OK );
425 Path::isDirectory() const {
427 if (0 != stat(path.c_str(), &buf))
429 return buf.st_mode & S_IFDIR ? true : false;
433 Path::canRead() const {
434 return 0 == access(path.c_str(), F_OK | R_OK );
438 Path::canWrite() const {
439 return 0 == access(path.c_str(), F_OK | W_OK );
443 Path::canExecute() const {
444 if (0 != access(path.c_str(), R_OK | X_OK ))
447 if (0 != stat(path.c_str(), &buf))
449 if (!S_ISREG(buf.st_mode))
455 Path::getLast() const {
456 // Find the last slash
457 size_t pos = path.rfind('/');
459 // Handle the corner cases
460 if (pos == std::string::npos)
463 // If the last character is a slash
464 if (pos == path.length()-1) {
465 // Find the second to last slash
466 size_t pos2 = path.rfind('/', pos-1);
467 if (pos2 == std::string::npos)
468 return path.substr(0,pos);
470 return path.substr(pos2+1,pos-pos2-1);
472 // Return everything after the last slash
473 return path.substr(pos+1);
477 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
478 if (!fsIsValid || update) {
480 if (0 != stat(path.c_str(), &buf)) {
481 MakeErrMsg(ErrStr, path + ": can't get status of file");
484 status.fileSize = buf.st_size;
485 status.modTime.fromEpochTime(buf.st_mtime);
486 status.mode = buf.st_mode;
487 status.user = buf.st_uid;
488 status.group = buf.st_gid;
489 status.uniqueID = uint64_t(buf.st_ino);
490 status.isDir = S_ISDIR(buf.st_mode);
491 status.isFile = S_ISREG(buf.st_mode);
497 static bool AddPermissionBits(const Path &File, int bits) {
498 // Get the umask value from the operating system. We want to use it
499 // when changing the file's permissions. Since calling umask() sets
500 // the umask and returns its old value, we must call it a second
501 // time to reset it to the user's preference.
502 int mask = umask(0777); // The arg. to umask is arbitrary.
503 umask(mask); // Restore the umask.
505 // Get the file's current mode.
507 if (0 != stat(File.toString().c_str(), &buf))
509 // Change the file to have whichever permissions bits from 'bits'
510 // that the umask would not disable.
511 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
516 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
517 if (!AddPermissionBits(*this, 0444))
518 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
522 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
523 if (!AddPermissionBits(*this, 0222))
524 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
528 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
529 if (!AddPermissionBits(*this, 0111))
530 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
535 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
536 DIR* direntries = ::opendir(path.c_str());
538 return MakeErrMsg(ErrMsg, path + ": can't open directory");
540 std::string dirPath = path;
541 if (!lastIsSlash(dirPath))
545 struct dirent* de = ::readdir(direntries);
546 for ( ; de != 0; de = ::readdir(direntries)) {
547 if (de->d_name[0] != '.') {
548 Path aPath(dirPath + (const char*)de->d_name);
550 if (0 != lstat(aPath.path.c_str(), &st)) {
551 if (S_ISLNK(st.st_mode))
552 continue; // dangling symlink -- ignore
553 return MakeErrMsg(ErrMsg,
554 aPath.path + ": can't determine file object type");
556 result.insert(aPath);
560 closedir(direntries);
565 Path::set(const std::string& a_path) {
568 std::string save(path);
578 Path::appendComponent(const std::string& name) {
581 std::string save(path);
582 if (!lastIsSlash(path))
593 Path::eraseComponent() {
594 size_t slashpos = path.rfind('/',path.size());
595 if (slashpos == 0 || slashpos == std::string::npos) {
599 if (slashpos == path.size() - 1)
600 slashpos = path.rfind('/',slashpos-1);
601 if (slashpos == std::string::npos) {
605 path.erase(slashpos);
610 Path::appendSuffix(const std::string& suffix) {
611 std::string save(path);
622 Path::eraseSuffix() {
623 std::string save = path;
624 size_t dotpos = path.rfind('.',path.size());
625 size_t slashpos = path.rfind('/',path.size());
626 if (dotpos != std::string::npos) {
627 if (slashpos == std::string::npos || dotpos > slashpos+1) {
628 path.erase(dotpos, path.size()-dotpos);
637 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
639 if (access(beg, F_OK | R_OK | W_OK) == 0)
642 if (create_parents) {
646 for (; c != beg; --c)
649 // Recurse to handling the parent directory.
651 bool x = createDirectoryHelper(beg, c, create_parents);
654 // Return if we encountered an error.
662 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
666 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
667 // Get a writeable copy of the path name
668 char pathname[MAXPATHLEN];
669 path.copy(pathname,MAXPATHLEN);
671 // Null-terminate the last component
672 size_t lastchar = path.length() - 1 ;
674 if (pathname[lastchar] != '/')
677 pathname[lastchar] = 0;
679 if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
680 return MakeErrMsg(ErrMsg,
681 std::string(pathname) + ": can't create directory");
687 Path::createFileOnDisk(std::string* ErrMsg) {
689 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
691 return MakeErrMsg(ErrMsg, path + ": can't create file");
697 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
698 // Make this into a unique file name
699 if (makeUnique( reuse_current, ErrMsg ))
703 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
705 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
711 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
712 // Get the status so we can determin if its a file or directory
714 if (0 != stat(path.c_str(), &buf)) {
715 MakeErrMsg(ErrStr, path + ": can't get status of file");
719 // Note: this check catches strange situations. In all cases, LLVM should
720 // only be involved in the creation and deletion of regular files. This
721 // check ensures that what we're trying to erase is a regular file. It
722 // effectively prevents LLVM from erasing things like /dev/null, any block
723 // special file, or other things that aren't "regular" files.
724 if (S_ISREG(buf.st_mode)) {
725 if (unlink(path.c_str()) != 0)
726 return MakeErrMsg(ErrStr, path + ": can't destroy file");
730 if (!S_ISDIR(buf.st_mode)) {
731 if (ErrStr) *ErrStr = "not a file or directory";
735 if (remove_contents) {
736 // Recursively descend the directory to remove its contents.
737 std::string cmd = "/bin/rm -rf " + path;
738 if (system(cmd.c_str()) != 0) {
739 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
745 // Otherwise, try to just remove the one directory.
746 char pathname[MAXPATHLEN];
747 path.copy(pathname, MAXPATHLEN);
748 size_t lastchar = path.length() - 1;
749 if (pathname[lastchar] == '/')
750 pathname[lastchar] = 0;
752 pathname[lastchar+1] = 0;
754 if (rmdir(pathname) != 0)
755 return MakeErrMsg(ErrStr,
756 std::string(pathname) + ": can't erase directory");
761 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
762 if (0 != ::rename(path.c_str(), newName.c_str()))
763 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
764 newName.toString() + "'");
769 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
771 utb.actime = si.modTime.toPosixTime();
772 utb.modtime = utb.actime;
773 if (0 != ::utime(path.c_str(),&utb))
774 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
775 if (0 != ::chmod(path.c_str(),si.mode))
776 return MakeErrMsg(ErrStr, path + ": can't set mode");
781 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
784 inFile = ::open(Src.c_str(), O_RDONLY);
786 return MakeErrMsg(ErrMsg, Src.toString() +
787 ": can't open source file to copy");
789 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
792 return MakeErrMsg(ErrMsg, Dest.toString() +
793 ": can't create destination file for copy");
796 char Buffer[16*1024];
797 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
799 if (errno != EINTR && errno != EAGAIN) {
802 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file");
805 char *BufPtr = Buffer;
807 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
808 if (AmtWritten == -1) {
809 if (errno != EINTR && errno != EAGAIN) {
812 return MakeErrMsg(ErrMsg, Dest.toString() +
813 ": can't write destination file");
817 BufPtr += AmtWritten;
828 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
829 if (reuse_current && !exists())
830 return false; // File doesn't exist already, just use it!
832 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
833 // mktemp or our own implementation.
834 char *FNBuffer = (char*) alloca(path.size()+8);
835 path.copy(FNBuffer,path.size());
837 strcpy(FNBuffer+path.size(), "/XXXXXX");
839 strcpy(FNBuffer+path.size(), "-XXXXXX");
841 #if defined(HAVE_MKSTEMP)
843 if ((TempFD = mkstemp(FNBuffer)) == -1)
844 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
846 // We don't need to hold the temp file descriptor... we will trust that no one
847 // will overwrite/delete the file before we can open it again.
852 #elif defined(HAVE_MKTEMP)
853 // If we don't have mkstemp, use the old and obsolete mktemp function.
854 if (mktemp(FNBuffer) == 0)
855 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
860 // Okay, looks like we have to do it all by our lonesome.
861 static unsigned FCounter = 0;
862 unsigned offset = path.size() + 1;
863 while ( FCounter < 999999 && exists()) {
864 sprintf(FNBuffer+offset,"%06u",++FCounter);
867 if (FCounter > 999999)
868 return MakeErrMsg(ErrMsg,
869 path + ": can't make unique filename: too many files");
874 const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
875 int Flags = MAP_PRIVATE;
879 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
880 if (BasePtr == MAP_FAILED)
882 return (const char*)BasePtr;
885 void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
886 ::munmap((void*)BasePtr, FileSize);
889 } // end llvm namespace