1 //===- llvm/Support/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 // Empty paths are considered invalid here.
100 // This code doesn't check MAXPATHLEN because there's no need. Nothing in
101 // LLVM manipulates Paths with fixed-sizes arrays, and if the OS can't
102 // handle names longer than some limit, it'll report this on demand using
104 return !path.empty();
108 Path::isAbsolute(const char *NameStart, unsigned NameLen) {
112 return NameStart[0] == '/';
116 Path::isAbsolute() const {
119 return path[0] == '/';
123 Path::GetRootDirectory() {
130 Path::GetTemporaryDirectory(std::string *ErrMsg) {
131 #if defined(HAVE_MKDTEMP)
132 // The best way is with mkdtemp but that's not available on many systems,
133 // Linux and FreeBSD have it. Others probably won't.
134 char pathname[] = "/tmp/llvm_XXXXXX";
135 if (0 == mkdtemp(pathname)) {
137 std::string(pathname) + ": can't create temporary directory");
140 return Path(pathname);
141 #elif defined(HAVE_MKSTEMP)
142 // If no mkdtemp is available, mkstemp can be used to create a temporary file
143 // which is then removed and created as a directory. We prefer this over
144 // mktemp because of mktemp's inherent security and threading risks. We still
145 // have a slight race condition from the time the temporary file is created to
146 // the time it is re-created as a directoy.
147 char pathname[] = "/tmp/llvm_XXXXXX";
149 if (-1 == (fd = mkstemp(pathname))) {
151 std::string(pathname) + ": can't create temporary directory");
155 ::unlink(pathname); // start race condition, ignore errors
156 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
158 std::string(pathname) + ": can't create temporary directory");
161 return Path(pathname);
162 #elif defined(HAVE_MKTEMP)
163 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
164 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
165 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
166 // the XXXXXX with the pid of the process and a letter. That leads to only
167 // twenty six temporary files that can be generated.
168 char pathname[] = "/tmp/llvm_XXXXXX";
169 char *TmpName = ::mktemp(pathname);
172 std::string(TmpName) + ": can't create unique directory name");
175 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
177 std::string(TmpName) + ": can't create temporary directory");
180 return Path(TmpName);
182 // This is the worst case implementation. tempnam(3) leaks memory unless its
183 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
184 // issues. The mktemp(3) function doesn't have enough variability in the
185 // temporary name generated. So, we provide our own implementation that
186 // increments an integer from a random number seeded by the current time. This
187 // should be sufficiently unique that we don't have many collisions between
188 // processes. Generally LLVM processes don't run very long and don't use very
189 // many temporary files so this shouldn't be a big issue for LLVM.
190 static time_t num = ::time(0);
191 char pathname[MAXPATHLEN];
194 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
195 } while ( 0 == access(pathname, F_OK ) );
196 if (-1 == ::mkdir(pathname, S_IRWXU)) {
198 std::string(pathname) + ": can't create temporary directory");
201 return Path(pathname);
206 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
207 #ifdef LTDL_SHLIBPATH_VAR
208 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
210 getPathList(env_var,Paths);
213 // FIXME: Should this look at LD_LIBRARY_PATH too?
214 Paths.push_back(sys::Path("/usr/local/lib/"));
215 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
216 Paths.push_back(sys::Path("/usr/lib/"));
217 Paths.push_back(sys::Path("/lib/"));
221 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
222 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
224 getPathList(env_var,Paths);
229 if (tmpPath.set(LLVM_LIBDIR))
230 if (tmpPath.canRead())
231 Paths.push_back(tmpPath);
234 GetSystemLibraryPaths(Paths);
238 Path::GetLLVMDefaultConfigDir() {
239 return Path("/etc/llvm/");
243 Path::GetUserHomeDirectory() {
244 const char* home = getenv("HOME");
247 if (result.set(home))
250 return GetRootDirectory();
254 Path::GetCurrentDirectory() {
255 char pathname[MAXPATHLEN];
256 if (!getcwd(pathname,MAXPATHLEN)) {
257 assert (false && "Could not query current working directory.");
261 return Path(pathname);
264 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__minix)
266 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
267 const char *dir, const char *bin)
271 snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
272 if (realpath(buf, ret) == NULL)
274 if (stat(buf, &sb) != 0)
281 getprogpath(char ret[PATH_MAX], const char *bin)
283 char *pv, *s, *t, buf[PATH_MAX];
285 /* First approach: absolute path. */
287 if (test_dir(buf, ret, "/", bin) == 0)
292 /* Second approach: relative path. */
293 if (strchr(bin, '/') != NULL) {
294 if (getcwd(buf, PATH_MAX) == NULL)
296 if (test_dir(buf, ret, buf, bin) == 0)
301 /* Third approach: $PATH */
302 if ((pv = getenv("PATH")) == NULL)
307 while ((t = strsep(&s, ":")) != NULL) {
308 if (test_dir(buf, ret, t, bin) == 0) {
316 #endif // __FreeBSD__ || __NetBSD__
318 /// GetMainExecutable - Return the path to the main executable, given the
319 /// value of argv[0] from program startup.
320 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
321 #if defined(__APPLE__)
322 // On OS X the executable path is saved to the stack by dyld. Reading it
323 // from there is much faster than calling dladdr, especially for large
324 // binaries with symbols.
325 char exe_path[MAXPATHLEN];
326 uint32_t size = sizeof(exe_path);
327 if (_NSGetExecutablePath(exe_path, &size) == 0) {
328 char link_path[MAXPATHLEN];
329 if (realpath(exe_path, link_path))
330 return Path(link_path);
332 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__minix)
333 char exe_path[PATH_MAX];
335 if (getprogpath(exe_path, argv0) != NULL)
336 return Path(exe_path);
337 #elif defined(__linux__) || defined(__CYGWIN__)
338 char exe_path[MAXPATHLEN];
339 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
341 return Path(StringRef(exe_path, len));
342 #elif defined(HAVE_DLFCN_H)
343 // Use dladdr to get executable path if available.
345 int err = dladdr(MainAddr, &DLInfo);
349 // If the filename is a symlink, we need to resolve and return the location of
350 // the actual executable.
351 char link_path[MAXPATHLEN];
352 if (realpath(DLInfo.dli_fname, link_path))
353 return Path(link_path);
355 #error GetMainExecutable is not implemented on this host yet.
361 StringRef Path::getDirname() const {
362 return getDirnameCharSep(path, "/");
366 Path::getBasename() const {
367 // Find the last slash
368 std::string::size_type slash = path.rfind('/');
369 if (slash == std::string::npos)
374 std::string::size_type dot = path.rfind('.');
375 if (dot == std::string::npos || dot < slash)
376 return StringRef(path).substr(slash);
378 return StringRef(path).substr(slash, dot - slash);
382 Path::getSuffix() const {
383 // Find the last slash
384 std::string::size_type slash = path.rfind('/');
385 if (slash == std::string::npos)
390 std::string::size_type dot = path.rfind('.');
391 if (dot == std::string::npos || dot < slash)
394 return StringRef(path).substr(dot + 1);
397 bool Path::getMagicNumber(std::string &Magic, unsigned len) const {
398 assert(len < 1024 && "Request for magic string too long");
400 int fd = ::open(path.c_str(), O_RDONLY);
403 ssize_t bytes_read = ::read(fd, Buf, len);
405 if (ssize_t(len) != bytes_read)
407 Magic.assign(Buf, len);
412 Path::exists() const {
413 return 0 == access(path.c_str(), F_OK );
417 Path::isDirectory() const {
419 if (0 != stat(path.c_str(), &buf))
421 return ((buf.st_mode & S_IFMT) == S_IFDIR) ? true : false;
425 Path::isSymLink() const {
427 if (0 != lstat(path.c_str(), &buf))
429 return S_ISLNK(buf.st_mode);
434 Path::canRead() const {
435 return 0 == access(path.c_str(), R_OK);
439 Path::canWrite() const {
440 return 0 == access(path.c_str(), W_OK);
444 Path::isRegularFile() const {
445 // Get the status so we can determine if it's a file or directory
448 if (0 != stat(path.c_str(), &buf))
451 if (S_ISREG(buf.st_mode))
458 Path::canExecute() const {
459 if (0 != access(path.c_str(), R_OK | X_OK ))
462 if (0 != stat(path.c_str(), &buf))
464 if (!S_ISREG(buf.st_mode))
470 Path::getLast() const {
471 // Find the last slash
472 size_t pos = path.rfind('/');
474 // Handle the corner cases
475 if (pos == std::string::npos)
478 // If the last character is a slash
479 if (pos == path.length()-1) {
480 // Find the second to last slash
481 size_t pos2 = path.rfind('/', pos-1);
482 if (pos2 == std::string::npos)
483 return StringRef(path).substr(0,pos);
485 return StringRef(path).substr(pos2+1,pos-pos2-1);
487 // Return everything after the last slash
488 return StringRef(path).substr(pos+1);
492 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
493 if (!fsIsValid || update) {
495 if (0 != stat(path.c_str(), &buf)) {
496 MakeErrMsg(ErrStr, path + ": can't get status of file");
499 status.fileSize = buf.st_size;
500 status.modTime.fromEpochTime(buf.st_mtime);
501 status.mode = buf.st_mode;
502 status.user = buf.st_uid;
503 status.group = buf.st_gid;
504 status.uniqueID = uint64_t(buf.st_ino);
505 status.isDir = S_ISDIR(buf.st_mode);
506 status.isFile = S_ISREG(buf.st_mode);
512 static bool AddPermissionBits(const Path &File, int bits) {
513 // Get the umask value from the operating system. We want to use it
514 // when changing the file's permissions. Since calling umask() sets
515 // the umask and returns its old value, we must call it a second
516 // time to reset it to the user's preference.
517 int mask = umask(0777); // The arg. to umask is arbitrary.
518 umask(mask); // Restore the umask.
520 // Get the file's current mode.
522 if (0 != stat(File.c_str(), &buf))
524 // Change the file to have whichever permissions bits from 'bits'
525 // that the umask would not disable.
526 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
531 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
532 if (!AddPermissionBits(*this, 0444))
533 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
537 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
538 if (!AddPermissionBits(*this, 0222))
539 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
543 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
544 if (!AddPermissionBits(*this, 0111))
545 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
550 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
551 DIR* direntries = ::opendir(path.c_str());
553 return MakeErrMsg(ErrMsg, path + ": can't open directory");
555 std::string dirPath = path;
556 if (!lastIsSlash(dirPath))
560 struct dirent* de = ::readdir(direntries);
561 for ( ; de != 0; de = ::readdir(direntries)) {
562 if (de->d_name[0] != '.') {
563 Path aPath(dirPath + (const char*)de->d_name);
565 if (0 != lstat(aPath.path.c_str(), &st)) {
566 if (S_ISLNK(st.st_mode))
567 continue; // dangling symlink -- ignore
568 return MakeErrMsg(ErrMsg,
569 aPath.path + ": can't determine file object type");
571 result.insert(aPath);
575 closedir(direntries);
580 Path::set(StringRef a_path) {
588 Path::appendComponent(StringRef name) {
591 if (!lastIsSlash(path))
598 Path::eraseComponent() {
599 size_t slashpos = path.rfind('/',path.size());
600 if (slashpos == 0 || slashpos == std::string::npos) {
604 if (slashpos == path.size() - 1)
605 slashpos = path.rfind('/',slashpos-1);
606 if (slashpos == std::string::npos) {
610 path.erase(slashpos);
615 Path::eraseSuffix() {
616 size_t dotpos = path.rfind('.',path.size());
617 size_t slashpos = path.rfind('/',path.size());
618 if (dotpos != std::string::npos) {
619 if (slashpos == std::string::npos || dotpos > slashpos+1) {
620 path.erase(dotpos, path.size()-dotpos);
627 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
629 if (access(beg, R_OK | W_OK) == 0)
632 if (create_parents) {
636 for (; c != beg; --c)
639 // Recurse to handling the parent directory.
641 bool x = createDirectoryHelper(beg, c, create_parents);
644 // Return if we encountered an error.
652 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
656 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
657 // Get a writeable copy of the path name
658 std::string pathname(path);
660 // Null-terminate the last component
661 size_t lastchar = path.length() - 1 ;
663 if (pathname[lastchar] != '/')
666 pathname[lastchar] = '\0';
668 if (createDirectoryHelper(&pathname[0], &pathname[lastchar], create_parents))
669 return MakeErrMsg(ErrMsg, pathname + ": can't create directory");
675 Path::createFileOnDisk(std::string* ErrMsg) {
677 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
679 return MakeErrMsg(ErrMsg, path + ": can't create file");
685 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
686 // Make this into a unique file name
687 if (makeUnique( reuse_current, ErrMsg ))
691 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
693 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
699 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
700 // Get the status so we can determine if it's a file or directory.
702 if (0 != stat(path.c_str(), &buf)) {
703 MakeErrMsg(ErrStr, path + ": can't get status of file");
707 // Note: this check catches strange situations. In all cases, LLVM should
708 // only be involved in the creation and deletion of regular files. This
709 // check ensures that what we're trying to erase is a regular file. It
710 // effectively prevents LLVM from erasing things like /dev/null, any block
711 // special file, or other things that aren't "regular" files.
712 if (S_ISREG(buf.st_mode)) {
713 if (unlink(path.c_str()) != 0)
714 return MakeErrMsg(ErrStr, path + ": can't destroy file");
718 if (!S_ISDIR(buf.st_mode)) {
719 if (ErrStr) *ErrStr = "not a file or directory";
723 if (remove_contents) {
724 // Recursively descend the directory to remove its contents.
725 std::string cmd = "/bin/rm -rf " + path;
726 if (system(cmd.c_str()) != 0) {
727 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
733 // Otherwise, try to just remove the one directory.
734 std::string pathname(path);
735 size_t lastchar = path.length() - 1;
736 if (pathname[lastchar] == '/')
737 pathname[lastchar] = '\0';
739 pathname[lastchar+1] = '\0';
741 if (rmdir(pathname.c_str()) != 0)
742 return MakeErrMsg(ErrStr, pathname + ": can't erase directory");
747 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
748 if (0 != ::rename(path.c_str(), newName.c_str()))
749 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
750 newName.str() + "'");
755 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
757 utb.actime = si.modTime.toPosixTime();
758 utb.modtime = utb.actime;
759 if (0 != ::utime(path.c_str(),&utb))
760 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
761 if (0 != ::chmod(path.c_str(),si.mode))
762 return MakeErrMsg(ErrStr, path + ": can't set mode");
767 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
770 inFile = ::open(Src.c_str(), O_RDONLY);
772 return MakeErrMsg(ErrMsg, Src.str() +
773 ": can't open source file to copy");
775 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
778 return MakeErrMsg(ErrMsg, Dest.str() +
779 ": can't create destination file for copy");
782 char Buffer[16*1024];
783 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
785 if (errno != EINTR && errno != EAGAIN) {
788 return MakeErrMsg(ErrMsg, Src.str()+": can't read source file");
791 char *BufPtr = Buffer;
793 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
794 if (AmtWritten == -1) {
795 if (errno != EINTR && errno != EAGAIN) {
798 return MakeErrMsg(ErrMsg, Dest.str() +
799 ": can't write destination file");
803 BufPtr += AmtWritten;
814 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
815 if (reuse_current && !exists())
816 return false; // File doesn't exist already, just use it!
818 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
819 // mktemp or our own implementation.
820 // This uses std::vector instead of SmallVector to avoid a dependence on
821 // libSupport. And performance isn't critical here.
822 std::vector<char> Buf;
823 Buf.resize(path.size()+8);
824 char *FNBuffer = &Buf[0];
825 path.copy(FNBuffer,path.size());
827 strcpy(FNBuffer+path.size(), "/XXXXXX");
829 strcpy(FNBuffer+path.size(), "-XXXXXX");
831 #if defined(HAVE_MKSTEMP)
833 if ((TempFD = mkstemp(FNBuffer)) == -1)
834 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
836 // We don't need to hold the temp file descriptor... we will trust that no one
837 // will overwrite/delete the file before we can open it again.
842 #elif defined(HAVE_MKTEMP)
843 // If we don't have mkstemp, use the old and obsolete mktemp function.
844 if (mktemp(FNBuffer) == 0)
845 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
850 // Okay, looks like we have to do it all by our lonesome.
851 static unsigned FCounter = 0;
852 // Try to initialize with unique value.
853 if (FCounter == 0) FCounter = ((unsigned)getpid() & 0xFFFF) << 8;
854 char* pos = strstr(FNBuffer, "XXXXXX");
856 if (++FCounter > 0xFFFFFF) {
857 return MakeErrMsg(ErrMsg,
858 path + ": can't make unique filename: too many files");
860 sprintf(pos, "%06X", FCounter);
863 // POSSIBLE SECURITY BUG: An attacker can easily guess the name and exploit
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