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 //===----------------------------------------------------------------------===//
26 #ifdef HAVE_SYS_MMAN_H
29 #ifdef HAVE_SYS_STAT_H
40 # define NAMLEN(dirent) strlen((dirent)->d_name)
42 # define dirent direct
43 # define NAMLEN(dirent) (dirent)->d_namlen
45 # include <sys/ndir.h>
60 #include <mach-o/dyld.h>
63 // Put in a hack for Cygwin which falsely reports that the mkdtemp function
64 // is available when it is not.
70 inline bool lastIsSlash(const std::string& path) {
71 return !path.empty() && path[path.length() - 1] == '/';
79 const char sys::PathSeparator = ':';
81 StringRef Path::GetEXESuffix() {
85 Path::Path(StringRef p)
88 Path::Path(const char *StrStart, unsigned StrLen)
89 : path(StrStart, StrLen) {}
92 Path::operator=(StringRef that) {
93 path.assign(that.data(), that.size());
98 Path::isValid() const {
99 // Check some obvious things
102 return path.length() < MAXPATHLEN;
106 Path::isAbsolute(const char *NameStart, unsigned NameLen) {
110 return NameStart[0] == '/';
114 Path::isAbsolute() const {
117 return path[0] == '/';
120 void Path::makeAbsolute() {
124 Path CWD = Path::GetCurrentDirectory();
125 assert(CWD.isAbsolute() && "GetCurrentDirectory returned relative path!");
127 CWD.appendComponent(path);
133 Path::GetRootDirectory() {
140 Path::GetTemporaryDirectory(std::string *ErrMsg) {
141 #if defined(HAVE_MKDTEMP)
142 // The best way is with mkdtemp but that's not available on many systems,
143 // Linux and FreeBSD have it. Others probably won't.
144 char pathname[MAXPATHLEN];
145 strcpy(pathname,"/tmp/llvm_XXXXXX");
146 if (0 == mkdtemp(pathname)) {
148 std::string(pathname) + ": can't create temporary directory");
152 result.set(pathname);
153 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
155 #elif defined(HAVE_MKSTEMP)
156 // If no mkdtemp is available, mkstemp can be used to create a temporary file
157 // which is then removed and created as a directory. We prefer this over
158 // mktemp because of mktemp's inherent security and threading risks. We still
159 // have a slight race condition from the time the temporary file is created to
160 // the time it is re-created as a directoy.
161 char pathname[MAXPATHLEN];
162 strcpy(pathname, "/tmp/llvm_XXXXXX");
164 if (-1 == (fd = mkstemp(pathname))) {
166 std::string(pathname) + ": can't create temporary directory");
170 ::unlink(pathname); // start race condition, ignore errors
171 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
173 std::string(pathname) + ": can't create temporary directory");
177 result.set(pathname);
178 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
180 #elif defined(HAVE_MKTEMP)
181 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
182 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
183 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
184 // the XXXXXX with the pid of the process and a letter. That leads to only
185 // twenty six temporary files that can be generated.
186 char pathname[MAXPATHLEN];
187 strcpy(pathname, "/tmp/llvm_XXXXXX");
188 char *TmpName = ::mktemp(pathname);
191 std::string(TmpName) + ": can't create unique directory name");
194 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
196 std::string(TmpName) + ": can't create temporary directory");
201 assert(result.isValid() && "mktemp didn't create a valid pathname!");
204 // This is the worst case implementation. tempnam(3) leaks memory unless its
205 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
206 // issues. The mktemp(3) function doesn't have enough variability in the
207 // temporary name generated. So, we provide our own implementation that
208 // increments an integer from a random number seeded by the current time. This
209 // should be sufficiently unique that we don't have many collisions between
210 // processes. Generally LLVM processes don't run very long and don't use very
211 // many temporary files so this shouldn't be a big issue for LLVM.
212 static time_t num = ::time(0);
213 char pathname[MAXPATHLEN];
216 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
217 } while ( 0 == access(pathname, F_OK ) );
218 if (-1 == ::mkdir(pathname, S_IRWXU)) {
220 std::string(pathname) + ": can't create temporary directory");
224 result.set(pathname);
225 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
231 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
232 #ifdef LTDL_SHLIBPATH_VAR
233 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
235 getPathList(env_var,Paths);
238 // FIXME: Should this look at LD_LIBRARY_PATH too?
239 Paths.push_back(sys::Path("/usr/local/lib/"));
240 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
241 Paths.push_back(sys::Path("/usr/lib/"));
242 Paths.push_back(sys::Path("/lib/"));
246 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
247 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
249 getPathList(env_var,Paths);
254 if (tmpPath.set(LLVM_LIBDIR))
255 if (tmpPath.canRead())
256 Paths.push_back(tmpPath);
259 GetSystemLibraryPaths(Paths);
263 Path::GetLLVMDefaultConfigDir() {
264 return Path("/etc/llvm/");
268 Path::GetUserHomeDirectory() {
269 const char* home = getenv("HOME");
272 if (result.set(home))
275 return GetRootDirectory();
279 Path::GetCurrentDirectory() {
280 char pathname[MAXPATHLEN];
281 if (!getcwd(pathname,MAXPATHLEN)) {
282 assert (false && "Could not query current working directory.");
286 return Path(pathname);
289 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__minix)
291 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
292 const char *dir, const char *bin)
296 snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
297 if (realpath(buf, ret) == NULL)
299 if (stat(buf, &sb) != 0)
306 getprogpath(char ret[PATH_MAX], const char *bin)
308 char *pv, *s, *t, buf[PATH_MAX];
310 /* First approach: absolute path. */
312 if (test_dir(buf, ret, "/", bin) == 0)
317 /* Second approach: relative path. */
318 if (strchr(bin, '/') != NULL) {
319 if (getcwd(buf, PATH_MAX) == NULL)
321 if (test_dir(buf, ret, buf, bin) == 0)
326 /* Third approach: $PATH */
327 if ((pv = getenv("PATH")) == NULL)
332 while ((t = strsep(&s, ":")) != NULL) {
333 if (test_dir(buf, ret, t, bin) == 0) {
341 #endif // __FreeBSD__ || __NetBSD__
343 /// GetMainExecutable - Return the path to the main executable, given the
344 /// value of argv[0] from program startup.
345 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
346 #if defined(__APPLE__)
347 // On OS X the executable path is saved to the stack by dyld. Reading it
348 // from there is much faster than calling dladdr, especially for large
349 // binaries with symbols.
350 char exe_path[MAXPATHLEN];
351 uint32_t size = sizeof(exe_path);
352 if (_NSGetExecutablePath(exe_path, &size) == 0) {
353 char link_path[MAXPATHLEN];
354 if (realpath(exe_path, link_path))
355 return Path(std::string(link_path));
357 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__minix)
358 char exe_path[PATH_MAX];
360 if (getprogpath(exe_path, argv0) != NULL)
361 return Path(std::string(exe_path));
362 #elif defined(__linux__) || defined(__CYGWIN__)
363 char exe_path[MAXPATHLEN];
364 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
366 return Path(std::string(exe_path, len));
367 #elif defined(HAVE_DLFCN_H)
368 // Use dladdr to get executable path if available.
370 int err = dladdr(MainAddr, &DLInfo);
374 // If the filename is a symlink, we need to resolve and return the location of
375 // the actual executable.
376 char link_path[MAXPATHLEN];
377 if (realpath(DLInfo.dli_fname, link_path))
378 return Path(std::string(link_path));
380 #error GetMainExecutable is not implemented on this host yet.
386 StringRef Path::getDirname() const {
387 return getDirnameCharSep(path, "/");
391 Path::getBasename() const {
392 // Find the last slash
393 std::string::size_type slash = path.rfind('/');
394 if (slash == std::string::npos)
399 std::string::size_type dot = path.rfind('.');
400 if (dot == std::string::npos || dot < slash)
401 return StringRef(path).substr(slash);
403 return StringRef(path).substr(slash, dot - slash);
407 Path::getSuffix() const {
408 // Find the last slash
409 std::string::size_type slash = path.rfind('/');
410 if (slash == std::string::npos)
415 std::string::size_type dot = path.rfind('.');
416 if (dot == std::string::npos || dot < slash)
419 return StringRef(path).substr(dot + 1);
422 bool Path::getMagicNumber(std::string &Magic, unsigned len) const {
423 assert(len < 1024 && "Request for magic string too long");
425 int fd = ::open(path.c_str(), O_RDONLY);
428 ssize_t bytes_read = ::read(fd, Buf, len);
430 if (ssize_t(len) != bytes_read)
432 Magic.assign(Buf, len);
437 Path::exists() const {
438 return 0 == access(path.c_str(), F_OK );
442 Path::isDirectory() const {
444 if (0 != stat(path.c_str(), &buf))
446 return ((buf.st_mode & S_IFMT) == S_IFDIR) ? true : false;
450 Path::canRead() const {
451 return 0 == access(path.c_str(), R_OK);
455 Path::canWrite() const {
456 return 0 == access(path.c_str(), W_OK);
460 Path::isRegularFile() const {
461 // Get the status so we can determine if it's a file or directory
464 if (0 != stat(path.c_str(), &buf))
467 if (S_ISREG(buf.st_mode))
474 Path::canExecute() const {
475 if (0 != access(path.c_str(), R_OK | X_OK ))
478 if (0 != stat(path.c_str(), &buf))
480 if (!S_ISREG(buf.st_mode))
486 Path::getLast() const {
487 // Find the last slash
488 size_t pos = path.rfind('/');
490 // Handle the corner cases
491 if (pos == std::string::npos)
494 // If the last character is a slash
495 if (pos == path.length()-1) {
496 // Find the second to last slash
497 size_t pos2 = path.rfind('/', pos-1);
498 if (pos2 == std::string::npos)
499 return StringRef(path).substr(0,pos);
501 return StringRef(path).substr(pos2+1,pos-pos2-1);
503 // Return everything after the last slash
504 return StringRef(path).substr(pos+1);
508 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
509 if (!fsIsValid || update) {
511 if (0 != stat(path.c_str(), &buf)) {
512 MakeErrMsg(ErrStr, path + ": can't get status of file");
515 status.fileSize = buf.st_size;
516 status.modTime.fromEpochTime(buf.st_mtime);
517 status.mode = buf.st_mode;
518 status.user = buf.st_uid;
519 status.group = buf.st_gid;
520 status.uniqueID = uint64_t(buf.st_ino);
521 status.isDir = S_ISDIR(buf.st_mode);
522 status.isFile = S_ISREG(buf.st_mode);
528 static bool AddPermissionBits(const Path &File, int bits) {
529 // Get the umask value from the operating system. We want to use it
530 // when changing the file's permissions. Since calling umask() sets
531 // the umask and returns its old value, we must call it a second
532 // time to reset it to the user's preference.
533 int mask = umask(0777); // The arg. to umask is arbitrary.
534 umask(mask); // Restore the umask.
536 // Get the file's current mode.
538 if (0 != stat(File.c_str(), &buf))
540 // Change the file to have whichever permissions bits from 'bits'
541 // that the umask would not disable.
542 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
547 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
548 if (!AddPermissionBits(*this, 0444))
549 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
553 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
554 if (!AddPermissionBits(*this, 0222))
555 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
559 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
560 if (!AddPermissionBits(*this, 0111))
561 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
566 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
567 DIR* direntries = ::opendir(path.c_str());
569 return MakeErrMsg(ErrMsg, path + ": can't open directory");
571 std::string dirPath = path;
572 if (!lastIsSlash(dirPath))
576 struct dirent* de = ::readdir(direntries);
577 for ( ; de != 0; de = ::readdir(direntries)) {
578 if (de->d_name[0] != '.') {
579 Path aPath(dirPath + (const char*)de->d_name);
581 if (0 != lstat(aPath.path.c_str(), &st)) {
582 if (S_ISLNK(st.st_mode))
583 continue; // dangling symlink -- ignore
584 return MakeErrMsg(ErrMsg,
585 aPath.path + ": can't determine file object type");
587 result.insert(aPath);
591 closedir(direntries);
596 Path::set(StringRef a_path) {
599 std::string save(path);
609 Path::appendComponent(StringRef name) {
612 std::string save(path);
613 if (!lastIsSlash(path))
624 Path::eraseComponent() {
625 size_t slashpos = path.rfind('/',path.size());
626 if (slashpos == 0 || slashpos == std::string::npos) {
630 if (slashpos == path.size() - 1)
631 slashpos = path.rfind('/',slashpos-1);
632 if (slashpos == std::string::npos) {
636 path.erase(slashpos);
641 Path::appendSuffix(StringRef suffix) {
642 std::string save(path);
653 Path::eraseSuffix() {
654 std::string save = path;
655 size_t dotpos = path.rfind('.',path.size());
656 size_t slashpos = path.rfind('/',path.size());
657 if (dotpos != std::string::npos) {
658 if (slashpos == std::string::npos || dotpos > slashpos+1) {
659 path.erase(dotpos, path.size()-dotpos);
668 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
670 if (access(beg, R_OK | W_OK) == 0)
673 if (create_parents) {
677 for (; c != beg; --c)
680 // Recurse to handling the parent directory.
682 bool x = createDirectoryHelper(beg, c, create_parents);
685 // Return if we encountered an error.
693 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
697 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
698 // Get a writeable copy of the path name
699 char pathname[MAXPATHLEN];
700 path.copy(pathname,MAXPATHLEN);
702 // Null-terminate the last component
703 size_t lastchar = path.length() - 1 ;
705 if (pathname[lastchar] != '/')
708 pathname[lastchar] = 0;
710 if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
711 return MakeErrMsg(ErrMsg,
712 std::string(pathname) + ": can't create directory");
718 Path::createFileOnDisk(std::string* ErrMsg) {
720 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
722 return MakeErrMsg(ErrMsg, path + ": can't create file");
728 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
729 // Make this into a unique file name
730 if (makeUnique( reuse_current, ErrMsg ))
734 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
736 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
742 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
743 // Get the status so we can determine if it's a file or directory.
745 if (0 != stat(path.c_str(), &buf)) {
746 MakeErrMsg(ErrStr, path + ": can't get status of file");
750 // Note: this check catches strange situations. In all cases, LLVM should
751 // only be involved in the creation and deletion of regular files. This
752 // check ensures that what we're trying to erase is a regular file. It
753 // effectively prevents LLVM from erasing things like /dev/null, any block
754 // special file, or other things that aren't "regular" files.
755 if (S_ISREG(buf.st_mode)) {
756 if (unlink(path.c_str()) != 0)
757 return MakeErrMsg(ErrStr, path + ": can't destroy file");
761 if (!S_ISDIR(buf.st_mode)) {
762 if (ErrStr) *ErrStr = "not a file or directory";
766 if (remove_contents) {
767 // Recursively descend the directory to remove its contents.
768 std::string cmd = "/bin/rm -rf " + path;
769 if (system(cmd.c_str()) != 0) {
770 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
776 // Otherwise, try to just remove the one directory.
777 char pathname[MAXPATHLEN];
778 path.copy(pathname, MAXPATHLEN);
779 size_t lastchar = path.length() - 1;
780 if (pathname[lastchar] == '/')
781 pathname[lastchar] = 0;
783 pathname[lastchar+1] = 0;
785 if (rmdir(pathname) != 0)
786 return MakeErrMsg(ErrStr,
787 std::string(pathname) + ": can't erase directory");
792 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
793 if (0 != ::rename(path.c_str(), newName.c_str()))
794 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
795 newName.str() + "'");
800 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
802 utb.actime = si.modTime.toPosixTime();
803 utb.modtime = utb.actime;
804 if (0 != ::utime(path.c_str(),&utb))
805 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
806 if (0 != ::chmod(path.c_str(),si.mode))
807 return MakeErrMsg(ErrStr, path + ": can't set mode");
812 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
815 inFile = ::open(Src.c_str(), O_RDONLY);
817 return MakeErrMsg(ErrMsg, Src.str() +
818 ": can't open source file to copy");
820 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
823 return MakeErrMsg(ErrMsg, Dest.str() +
824 ": can't create destination file for copy");
827 char Buffer[16*1024];
828 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
830 if (errno != EINTR && errno != EAGAIN) {
833 return MakeErrMsg(ErrMsg, Src.str()+": can't read source file");
836 char *BufPtr = Buffer;
838 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
839 if (AmtWritten == -1) {
840 if (errno != EINTR && errno != EAGAIN) {
843 return MakeErrMsg(ErrMsg, Dest.str() +
844 ": can't write destination file");
848 BufPtr += AmtWritten;
859 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
860 if (reuse_current && !exists())
861 return false; // File doesn't exist already, just use it!
863 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
864 // mktemp or our own implementation.
865 // This uses std::vector instead of SmallVector to avoid a dependence on
866 // libSupport. And performance isn't critical here.
867 std::vector<char> Buf;
868 Buf.resize(path.size()+8);
869 char *FNBuffer = &Buf[0];
870 path.copy(FNBuffer,path.size());
872 strcpy(FNBuffer+path.size(), "/XXXXXX");
874 strcpy(FNBuffer+path.size(), "-XXXXXX");
876 #if defined(HAVE_MKSTEMP)
878 if ((TempFD = mkstemp(FNBuffer)) == -1)
879 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
881 // We don't need to hold the temp file descriptor... we will trust that no one
882 // will overwrite/delete the file before we can open it again.
887 #elif defined(HAVE_MKTEMP)
888 // If we don't have mkstemp, use the old and obsolete mktemp function.
889 if (mktemp(FNBuffer) == 0)
890 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
895 // Okay, looks like we have to do it all by our lonesome.
896 static unsigned FCounter = 0;
897 // Try to initialize with unique value.
898 if (FCounter == 0) FCounter = ((unsigned)getpid() & 0xFFFF) << 8;
899 char* pos = strstr(FNBuffer, "XXXXXX");
901 if (++FCounter > 0xFFFFFF) {
902 return MakeErrMsg(ErrMsg,
903 path + ": can't make unique filename: too many files");
905 sprintf(pos, "%06X", FCounter);
908 // POSSIBLE SECURITY BUG: An attacker can easily guess the name and exploit
914 const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
915 int Flags = MAP_PRIVATE;
919 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
920 if (BasePtr == MAP_FAILED)
922 return (const char*)BasePtr;
925 void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
926 ::munmap((void*)BasePtr, FileSize);
929 } // end llvm namespace