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>
64 #if defined(__GNU__) && !defined(MAXPATHLEN)
65 # define MAXPATHLEN 4096
68 // Put in a hack for Cygwin which falsely reports that the mkdtemp function
69 // is available when it is not.
75 inline bool lastIsSlash(const std::string& path) {
76 return !path.empty() && path[path.length() - 1] == '/';
84 const char sys::PathSeparator = ':';
86 StringRef Path::GetEXESuffix() {
90 Path::Path(StringRef p)
93 Path::Path(const char *StrStart, unsigned StrLen)
94 : path(StrStart, StrLen) {}
97 Path::operator=(StringRef that) {
98 path.assign(that.data(), that.size());
103 Path::isValid() const {
104 // Empty paths are considered invalid here.
105 // This code doesn't check MAXPATHLEN because there's no need. Nothing in
106 // LLVM manipulates Paths with fixed-sizes arrays, and if the OS can't
107 // handle names longer than some limit, it'll report this on demand using
109 return !path.empty();
113 Path::isAbsolute(const char *NameStart, unsigned NameLen) {
117 return NameStart[0] == '/';
121 Path::isAbsolute() const {
124 return path[0] == '/';
128 Path::GetRootDirectory() {
135 Path::GetTemporaryDirectory(std::string *ErrMsg) {
136 #if defined(HAVE_MKDTEMP)
137 // The best way is with mkdtemp but that's not available on many systems,
138 // Linux and FreeBSD have it. Others probably won't.
139 char pathname[] = "/tmp/llvm_XXXXXX";
140 if (0 == mkdtemp(pathname)) {
142 std::string(pathname) + ": can't create temporary directory");
145 return Path(pathname);
146 #elif defined(HAVE_MKSTEMP)
147 // If no mkdtemp is available, mkstemp can be used to create a temporary file
148 // which is then removed and created as a directory. We prefer this over
149 // mktemp because of mktemp's inherent security and threading risks. We still
150 // have a slight race condition from the time the temporary file is created to
151 // the time it is re-created as a directoy.
152 char pathname[] = "/tmp/llvm_XXXXXX";
154 if (-1 == (fd = mkstemp(pathname))) {
156 std::string(pathname) + ": can't create temporary directory");
160 ::unlink(pathname); // start race condition, ignore errors
161 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
163 std::string(pathname) + ": can't create temporary directory");
166 return Path(pathname);
167 #elif defined(HAVE_MKTEMP)
168 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
169 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
170 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
171 // the XXXXXX with the pid of the process and a letter. That leads to only
172 // twenty six temporary files that can be generated.
173 char pathname[] = "/tmp/llvm_XXXXXX";
174 char *TmpName = ::mktemp(pathname);
177 std::string(TmpName) + ": can't create unique directory name");
180 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
182 std::string(TmpName) + ": can't create temporary directory");
185 return Path(TmpName);
187 // This is the worst case implementation. tempnam(3) leaks memory unless its
188 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
189 // issues. The mktemp(3) function doesn't have enough variability in the
190 // temporary name generated. So, we provide our own implementation that
191 // increments an integer from a random number seeded by the current time. This
192 // should be sufficiently unique that we don't have many collisions between
193 // processes. Generally LLVM processes don't run very long and don't use very
194 // many temporary files so this shouldn't be a big issue for LLVM.
195 static time_t num = ::time(0);
196 char pathname[MAXPATHLEN];
199 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
200 } while ( 0 == access(pathname, F_OK ) );
201 if (-1 == ::mkdir(pathname, S_IRWXU)) {
203 std::string(pathname) + ": can't create temporary directory");
206 return Path(pathname);
211 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
212 #ifdef LTDL_SHLIBPATH_VAR
213 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
215 getPathList(env_var,Paths);
218 // FIXME: Should this look at LD_LIBRARY_PATH too?
219 Paths.push_back(sys::Path("/usr/local/lib/"));
220 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
221 Paths.push_back(sys::Path("/usr/lib/"));
222 Paths.push_back(sys::Path("/lib/"));
226 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
227 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
229 getPathList(env_var,Paths);
234 if (tmpPath.set(LLVM_LIBDIR))
235 if (tmpPath.canRead())
236 Paths.push_back(tmpPath);
239 GetSystemLibraryPaths(Paths);
243 Path::GetUserHomeDirectory() {
244 const char* home = getenv("HOME");
246 if (home && result.set(home))
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 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
264 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
265 defined(__linux__) || defined(__CYGWIN__)
267 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
268 const char *dir, const char *bin)
272 snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
273 if (realpath(buf, ret) == NULL)
275 if (stat(buf, &sb) != 0)
282 getprogpath(char ret[PATH_MAX], const char *bin)
284 char *pv, *s, *t, buf[PATH_MAX];
286 /* First approach: absolute path. */
288 if (test_dir(buf, ret, "/", bin) == 0)
293 /* Second approach: relative path. */
294 if (strchr(bin, '/') != NULL) {
295 if (getcwd(buf, PATH_MAX) == NULL)
297 if (test_dir(buf, ret, buf, bin) == 0)
302 /* Third approach: $PATH */
303 if ((pv = getenv("PATH")) == NULL)
308 while ((t = strsep(&s, ":")) != NULL) {
309 if (test_dir(buf, ret, t, bin) == 0) {
317 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
319 /// GetMainExecutable - Return the path to the main executable, given the
320 /// value of argv[0] from program startup.
321 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
322 #if defined(__APPLE__)
323 // On OS X the executable path is saved to the stack by dyld. Reading it
324 // from there is much faster than calling dladdr, especially for large
325 // binaries with symbols.
326 char exe_path[MAXPATHLEN];
327 uint32_t size = sizeof(exe_path);
328 if (_NSGetExecutablePath(exe_path, &size) == 0) {
329 char link_path[MAXPATHLEN];
330 if (realpath(exe_path, link_path))
331 return Path(link_path);
333 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
334 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__)
335 char exe_path[PATH_MAX];
337 if (getprogpath(exe_path, argv0) != NULL)
338 return Path(exe_path);
339 #elif defined(__linux__) || defined(__CYGWIN__)
340 char exe_path[MAXPATHLEN];
341 StringRef aPath("/proc/self/exe");
342 if (sys::fs::exists(aPath)) {
343 // /proc is not always mounted under Linux (chroot for example).
344 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
346 return Path(StringRef(exe_path, len));
348 // Fall back to the classical detection.
349 if (getprogpath(exe_path, argv0) != NULL)
350 return Path(exe_path);
352 #elif defined(HAVE_DLFCN_H)
353 // Use dladdr to get executable path if available.
355 int err = dladdr(MainAddr, &DLInfo);
359 // If the filename is a symlink, we need to resolve and return the location of
360 // the actual executable.
361 char link_path[MAXPATHLEN];
362 if (realpath(DLInfo.dli_fname, link_path))
363 return Path(link_path);
365 #error GetMainExecutable is not implemented on this host yet.
371 StringRef Path::getDirname() const {
372 return getDirnameCharSep(path, "/");
376 Path::getBasename() const {
377 // Find the last slash
378 std::string::size_type slash = path.rfind('/');
379 if (slash == std::string::npos)
384 std::string::size_type dot = path.rfind('.');
385 if (dot == std::string::npos || dot < slash)
386 return StringRef(path).substr(slash);
388 return StringRef(path).substr(slash, dot - slash);
392 Path::getSuffix() const {
393 // Find the last slash
394 std::string::size_type slash = path.rfind('/');
395 if (slash == std::string::npos)
400 std::string::size_type dot = path.rfind('.');
401 if (dot == std::string::npos || dot < slash)
404 return StringRef(path).substr(dot + 1);
407 bool Path::getMagicNumber(std::string &Magic, unsigned len) const {
408 assert(len < 1024 && "Request for magic string too long");
410 int fd = ::open(path.c_str(), O_RDONLY);
413 ssize_t bytes_read = ::read(fd, Buf, len);
415 if (ssize_t(len) != bytes_read)
417 Magic.assign(Buf, len);
422 Path::exists() const {
423 return 0 == access(path.c_str(), F_OK );
427 Path::isDirectory() const {
429 if (0 != stat(path.c_str(), &buf))
431 return ((buf.st_mode & S_IFMT) == S_IFDIR) ? true : false;
435 Path::isSymLink() const {
437 if (0 != lstat(path.c_str(), &buf))
439 return S_ISLNK(buf.st_mode);
444 Path::canRead() const {
445 return 0 == access(path.c_str(), R_OK);
449 Path::canWrite() const {
450 return 0 == access(path.c_str(), W_OK);
454 Path::isRegularFile() const {
455 // Get the status so we can determine if it's a file or directory
458 if (0 != stat(path.c_str(), &buf))
461 if (S_ISREG(buf.st_mode))
468 Path::canExecute() const {
469 if (0 != access(path.c_str(), R_OK | X_OK ))
472 if (0 != stat(path.c_str(), &buf))
474 if (!S_ISREG(buf.st_mode))
480 Path::getLast() const {
481 // Find the last slash
482 size_t pos = path.rfind('/');
484 // Handle the corner cases
485 if (pos == std::string::npos)
488 // If the last character is a slash
489 if (pos == path.length()-1) {
490 // Find the second to last slash
491 size_t pos2 = path.rfind('/', pos-1);
492 if (pos2 == std::string::npos)
493 return StringRef(path).substr(0,pos);
495 return StringRef(path).substr(pos2+1,pos-pos2-1);
497 // Return everything after the last slash
498 return StringRef(path).substr(pos+1);
502 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
503 if (!fsIsValid || update) {
505 if (0 != stat(path.c_str(), &buf)) {
506 MakeErrMsg(ErrStr, path + ": can't get status of file");
509 status.fileSize = buf.st_size;
510 status.modTime.fromEpochTime(buf.st_mtime);
511 status.mode = buf.st_mode;
512 status.user = buf.st_uid;
513 status.group = buf.st_gid;
514 status.uniqueID = uint64_t(buf.st_ino);
515 status.isDir = S_ISDIR(buf.st_mode);
516 status.isFile = S_ISREG(buf.st_mode);
522 static bool AddPermissionBits(const Path &File, int bits) {
523 // Get the umask value from the operating system. We want to use it
524 // when changing the file's permissions. Since calling umask() sets
525 // the umask and returns its old value, we must call it a second
526 // time to reset it to the user's preference.
527 int mask = umask(0777); // The arg. to umask is arbitrary.
528 umask(mask); // Restore the umask.
530 // Get the file's current mode.
532 if (0 != stat(File.c_str(), &buf))
534 // Change the file to have whichever permissions bits from 'bits'
535 // that the umask would not disable.
536 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
541 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
542 if (!AddPermissionBits(*this, 0444))
543 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
547 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
548 if (!AddPermissionBits(*this, 0222))
549 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
553 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
554 if (!AddPermissionBits(*this, 0111))
555 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
560 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
561 DIR* direntries = ::opendir(path.c_str());
563 return MakeErrMsg(ErrMsg, path + ": can't open directory");
565 std::string dirPath = path;
566 if (!lastIsSlash(dirPath))
570 struct dirent* de = ::readdir(direntries);
571 for ( ; de != 0; de = ::readdir(direntries)) {
572 if (de->d_name[0] != '.') {
573 Path aPath(dirPath + (const char*)de->d_name);
575 if (0 != lstat(aPath.path.c_str(), &st)) {
576 if (S_ISLNK(st.st_mode))
577 continue; // dangling symlink -- ignore
578 return MakeErrMsg(ErrMsg,
579 aPath.path + ": can't determine file object type");
581 result.insert(aPath);
585 closedir(direntries);
590 Path::set(StringRef a_path) {
598 Path::appendComponent(StringRef name) {
601 if (!lastIsSlash(path))
608 Path::eraseComponent() {
609 size_t slashpos = path.rfind('/',path.size());
610 if (slashpos == 0 || slashpos == std::string::npos) {
614 if (slashpos == path.size() - 1)
615 slashpos = path.rfind('/',slashpos-1);
616 if (slashpos == std::string::npos) {
620 path.erase(slashpos);
625 Path::eraseSuffix() {
626 size_t dotpos = path.rfind('.',path.size());
627 size_t slashpos = path.rfind('/',path.size());
628 if (dotpos != std::string::npos) {
629 if (slashpos == std::string::npos || dotpos > slashpos+1) {
630 path.erase(dotpos, path.size()-dotpos);
637 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
639 if (access(beg, 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 std::string pathname(path);
670 // Null-terminate the last component
671 size_t lastchar = path.length() - 1 ;
673 if (pathname[lastchar] != '/')
676 pathname[lastchar] = '\0';
678 if (createDirectoryHelper(&pathname[0], &pathname[lastchar], create_parents))
679 return MakeErrMsg(ErrMsg, pathname + ": can't create directory");
685 Path::createFileOnDisk(std::string* ErrMsg) {
687 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
689 return MakeErrMsg(ErrMsg, path + ": can't create file");
695 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
696 // Make this into a unique file name
697 if (makeUnique( reuse_current, ErrMsg ))
701 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
703 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
709 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
710 // Get the status so we can determine if it's a file or directory.
712 if (0 != stat(path.c_str(), &buf)) {
713 MakeErrMsg(ErrStr, path + ": can't get status of file");
717 // Note: this check catches strange situations. In all cases, LLVM should
718 // only be involved in the creation and deletion of regular files. This
719 // check ensures that what we're trying to erase is a regular file. It
720 // effectively prevents LLVM from erasing things like /dev/null, any block
721 // special file, or other things that aren't "regular" files.
722 if (S_ISREG(buf.st_mode)) {
723 if (unlink(path.c_str()) != 0)
724 return MakeErrMsg(ErrStr, path + ": can't destroy file");
728 if (!S_ISDIR(buf.st_mode)) {
729 if (ErrStr) *ErrStr = "not a file or directory";
733 if (remove_contents) {
734 // Recursively descend the directory to remove its contents.
735 std::string cmd = "/bin/rm -rf " + path;
736 if (system(cmd.c_str()) != 0) {
737 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
743 // Otherwise, try to just remove the one directory.
744 std::string pathname(path);
745 size_t lastchar = path.length() - 1;
746 if (pathname[lastchar] == '/')
747 pathname[lastchar] = '\0';
749 pathname[lastchar+1] = '\0';
751 if (rmdir(pathname.c_str()) != 0)
752 return MakeErrMsg(ErrStr, pathname + ": can't erase directory");
757 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
758 if (0 != ::rename(path.c_str(), newName.c_str()))
759 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
760 newName.str() + "'");
765 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
767 utb.actime = si.modTime.toPosixTime();
768 utb.modtime = utb.actime;
769 if (0 != ::utime(path.c_str(),&utb))
770 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
771 if (0 != ::chmod(path.c_str(),si.mode))
772 return MakeErrMsg(ErrStr, path + ": can't set mode");
777 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
780 inFile = ::open(Src.c_str(), O_RDONLY);
782 return MakeErrMsg(ErrMsg, Src.str() +
783 ": can't open source file to copy");
785 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
788 return MakeErrMsg(ErrMsg, Dest.str() +
789 ": can't create destination file for copy");
792 char Buffer[16*1024];
793 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
795 if (errno != EINTR && errno != EAGAIN) {
798 return MakeErrMsg(ErrMsg, Src.str()+": can't read source file");
801 char *BufPtr = Buffer;
803 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
804 if (AmtWritten == -1) {
805 if (errno != EINTR && errno != EAGAIN) {
808 return MakeErrMsg(ErrMsg, Dest.str() +
809 ": can't write destination file");
813 BufPtr += AmtWritten;
824 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
826 if (reuse_current && (fs::exists(path, Exists) || !Exists))
827 return false; // File doesn't exist already, just use it!
829 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
830 // mktemp or our own implementation.
831 // This uses std::vector instead of SmallVector to avoid a dependence on
832 // libSupport. And performance isn't critical here.
833 std::vector<char> Buf;
834 Buf.resize(path.size()+8);
835 char *FNBuffer = &Buf[0];
836 path.copy(FNBuffer,path.size());
838 if (!fs::is_directory(path, isdir) && isdir)
839 strcpy(FNBuffer+path.size(), "/XXXXXX");
841 strcpy(FNBuffer+path.size(), "-XXXXXX");
843 #if defined(HAVE_MKSTEMP)
845 if ((TempFD = mkstemp(FNBuffer)) == -1)
846 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
848 // We don't need to hold the temp file descriptor... we will trust that no one
849 // will overwrite/delete the file before we can open it again.
855 // By default mkstemp sets the mode to 0600, so update mode bits now.
856 AddPermissionBits (*this, 0666);
857 #elif defined(HAVE_MKTEMP)
858 // If we don't have mkstemp, use the old and obsolete mktemp function.
859 if (mktemp(FNBuffer) == 0)
860 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
865 // Okay, looks like we have to do it all by our lonesome.
866 static unsigned FCounter = 0;
867 // Try to initialize with unique value.
868 if (FCounter == 0) FCounter = ((unsigned)getpid() & 0xFFFF) << 8;
869 char* pos = strstr(FNBuffer, "XXXXXX");
871 if (++FCounter > 0xFFFFFF) {
872 return MakeErrMsg(ErrMsg,
873 path + ": can't make unique filename: too many files");
875 sprintf(pos, "%06X", FCounter);
878 // POSSIBLE SECURITY BUG: An attacker can easily guess the name and exploit
884 const char *Path::MapInFilePages(int FD, size_t FileSize, off_t Offset) {
885 int Flags = MAP_PRIVATE;
889 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, Offset);
890 if (BasePtr == MAP_FAILED)
892 return (const char*)BasePtr;
895 void Path::UnMapFilePages(const char *BasePtr, size_t FileSize) {
896 const void *Addr = static_cast<const void *>(BasePtr);
897 ::munmap(const_cast<void *>(Addr), FileSize);
900 } // end llvm namespace