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::GetUserHomeDirectory() {
227 const char* home = getenv("HOME");
229 if (home && result.set(home))
236 Path::GetCurrentDirectory() {
237 char pathname[MAXPATHLEN];
238 if (!getcwd(pathname, MAXPATHLEN)) {
239 assert(false && "Could not query current working directory.");
243 return Path(pathname);
246 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
247 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
248 defined(__linux__) || defined(__CYGWIN__)
250 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
251 const char *dir, const char *bin)
255 snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
256 if (realpath(buf, ret) == NULL)
258 if (stat(buf, &sb) != 0)
265 getprogpath(char ret[PATH_MAX], const char *bin)
267 char *pv, *s, *t, buf[PATH_MAX];
269 /* First approach: absolute path. */
271 if (test_dir(buf, ret, "/", bin) == 0)
276 /* Second approach: relative path. */
277 if (strchr(bin, '/') != NULL) {
278 if (getcwd(buf, PATH_MAX) == NULL)
280 if (test_dir(buf, ret, buf, bin) == 0)
285 /* Third approach: $PATH */
286 if ((pv = getenv("PATH")) == NULL)
291 while ((t = strsep(&s, ":")) != NULL) {
292 if (test_dir(buf, ret, t, bin) == 0) {
300 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
302 /// GetMainExecutable - Return the path to the main executable, given the
303 /// value of argv[0] from program startup.
304 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
305 #if defined(__APPLE__)
306 // On OS X the executable path is saved to the stack by dyld. Reading it
307 // from there is much faster than calling dladdr, especially for large
308 // binaries with symbols.
309 char exe_path[MAXPATHLEN];
310 uint32_t size = sizeof(exe_path);
311 if (_NSGetExecutablePath(exe_path, &size) == 0) {
312 char link_path[MAXPATHLEN];
313 if (realpath(exe_path, link_path))
314 return Path(link_path);
316 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
317 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__)
318 char exe_path[PATH_MAX];
320 if (getprogpath(exe_path, argv0) != NULL)
321 return Path(exe_path);
322 #elif defined(__linux__) || defined(__CYGWIN__)
323 char exe_path[MAXPATHLEN];
324 StringRef aPath("/proc/self/exe");
325 if (sys::fs::exists(aPath)) {
326 // /proc is not always mounted under Linux (chroot for example).
327 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
329 return Path(StringRef(exe_path, len));
331 // Fall back to the classical detection.
332 if (getprogpath(exe_path, argv0) != NULL)
333 return Path(exe_path);
335 #elif defined(HAVE_DLFCN_H)
336 // Use dladdr to get executable path if available.
338 int err = dladdr(MainAddr, &DLInfo);
342 // If the filename is a symlink, we need to resolve and return the location of
343 // the actual executable.
344 char link_path[MAXPATHLEN];
345 if (realpath(DLInfo.dli_fname, link_path))
346 return Path(link_path);
348 #error GetMainExecutable is not implemented on this host yet.
354 StringRef Path::getDirname() const {
355 return getDirnameCharSep(path, "/");
359 Path::getBasename() const {
360 // Find the last slash
361 std::string::size_type slash = path.rfind('/');
362 if (slash == std::string::npos)
367 std::string::size_type dot = path.rfind('.');
368 if (dot == std::string::npos || dot < slash)
369 return StringRef(path).substr(slash);
371 return StringRef(path).substr(slash, dot - slash);
375 Path::getSuffix() const {
376 // Find the last slash
377 std::string::size_type slash = path.rfind('/');
378 if (slash == std::string::npos)
383 std::string::size_type dot = path.rfind('.');
384 if (dot == std::string::npos || dot < slash)
387 return StringRef(path).substr(dot + 1);
390 bool Path::getMagicNumber(std::string &Magic, unsigned len) const {
391 assert(len < 1024 && "Request for magic string too long");
393 int fd = ::open(path.c_str(), O_RDONLY);
396 ssize_t bytes_read = ::read(fd, Buf, len);
398 if (ssize_t(len) != bytes_read)
400 Magic.assign(Buf, len);
405 Path::exists() const {
406 return 0 == access(path.c_str(), F_OK );
410 Path::isDirectory() const {
412 if (0 != stat(path.c_str(), &buf))
414 return ((buf.st_mode & S_IFMT) == S_IFDIR) ? true : false;
418 Path::isSymLink() const {
420 if (0 != lstat(path.c_str(), &buf))
422 return S_ISLNK(buf.st_mode);
427 Path::canRead() const {
428 return 0 == access(path.c_str(), R_OK);
432 Path::canWrite() const {
433 return 0 == access(path.c_str(), W_OK);
437 Path::isRegularFile() const {
438 // Get the status so we can determine if it's a file or directory
441 if (0 != stat(path.c_str(), &buf))
444 if (S_ISREG(buf.st_mode))
451 Path::canExecute() const {
452 if (0 != access(path.c_str(), R_OK | X_OK ))
455 if (0 != stat(path.c_str(), &buf))
457 if (!S_ISREG(buf.st_mode))
463 Path::getLast() const {
464 // Find the last slash
465 size_t pos = path.rfind('/');
467 // Handle the corner cases
468 if (pos == std::string::npos)
471 // If the last character is a slash
472 if (pos == path.length()-1) {
473 // Find the second to last slash
474 size_t pos2 = path.rfind('/', pos-1);
475 if (pos2 == std::string::npos)
476 return StringRef(path).substr(0,pos);
478 return StringRef(path).substr(pos2+1,pos-pos2-1);
480 // Return everything after the last slash
481 return StringRef(path).substr(pos+1);
485 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
486 if (!fsIsValid || update) {
488 if (0 != stat(path.c_str(), &buf)) {
489 MakeErrMsg(ErrStr, path + ": can't get status of file");
492 status.fileSize = buf.st_size;
493 status.modTime.fromEpochTime(buf.st_mtime);
494 status.mode = buf.st_mode;
495 status.user = buf.st_uid;
496 status.group = buf.st_gid;
497 status.uniqueID = uint64_t(buf.st_ino);
498 status.isDir = S_ISDIR(buf.st_mode);
499 status.isFile = S_ISREG(buf.st_mode);
505 static bool AddPermissionBits(const Path &File, int bits) {
506 // Get the umask value from the operating system. We want to use it
507 // when changing the file's permissions. Since calling umask() sets
508 // the umask and returns its old value, we must call it a second
509 // time to reset it to the user's preference.
510 int mask = umask(0777); // The arg. to umask is arbitrary.
511 umask(mask); // Restore the umask.
513 // Get the file's current mode.
515 if (0 != stat(File.c_str(), &buf))
517 // Change the file to have whichever permissions bits from 'bits'
518 // that the umask would not disable.
519 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
524 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
525 if (!AddPermissionBits(*this, 0444))
526 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
530 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
531 if (!AddPermissionBits(*this, 0222))
532 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
536 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
537 if (!AddPermissionBits(*this, 0111))
538 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
543 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
544 DIR* direntries = ::opendir(path.c_str());
546 return MakeErrMsg(ErrMsg, path + ": can't open directory");
548 std::string dirPath = path;
549 if (!lastIsSlash(dirPath))
553 struct dirent* de = ::readdir(direntries);
554 for ( ; de != 0; de = ::readdir(direntries)) {
555 if (de->d_name[0] != '.') {
556 Path aPath(dirPath + (const char*)de->d_name);
558 if (0 != lstat(aPath.path.c_str(), &st)) {
559 if (S_ISLNK(st.st_mode))
560 continue; // dangling symlink -- ignore
561 return MakeErrMsg(ErrMsg,
562 aPath.path + ": can't determine file object type");
564 result.insert(aPath);
568 closedir(direntries);
573 Path::set(StringRef a_path) {
581 Path::appendComponent(StringRef name) {
584 if (!lastIsSlash(path))
591 Path::eraseComponent() {
592 size_t slashpos = path.rfind('/',path.size());
593 if (slashpos == 0 || slashpos == std::string::npos) {
597 if (slashpos == path.size() - 1)
598 slashpos = path.rfind('/',slashpos-1);
599 if (slashpos == std::string::npos) {
603 path.erase(slashpos);
608 Path::eraseSuffix() {
609 size_t dotpos = path.rfind('.',path.size());
610 size_t slashpos = path.rfind('/',path.size());
611 if (dotpos != std::string::npos) {
612 if (slashpos == std::string::npos || dotpos > slashpos+1) {
613 path.erase(dotpos, path.size()-dotpos);
620 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
622 if (access(beg, R_OK | W_OK) == 0)
625 if (create_parents) {
629 for (; c != beg; --c)
632 // Recurse to handling the parent directory.
634 bool x = createDirectoryHelper(beg, c, create_parents);
637 // Return if we encountered an error.
645 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
649 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
650 // Get a writeable copy of the path name
651 std::string pathname(path);
653 // Null-terminate the last component
654 size_t lastchar = path.length() - 1 ;
656 if (pathname[lastchar] != '/')
659 pathname[lastchar] = '\0';
661 if (createDirectoryHelper(&pathname[0], &pathname[lastchar], create_parents))
662 return MakeErrMsg(ErrMsg, pathname + ": can't create directory");
668 Path::createFileOnDisk(std::string* ErrMsg) {
670 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
672 return MakeErrMsg(ErrMsg, path + ": can't create file");
678 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
679 // Make this into a unique file name
680 if (makeUnique( reuse_current, ErrMsg ))
684 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
686 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
692 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
693 // Get the status so we can determine if it's a file or directory.
695 if (0 != stat(path.c_str(), &buf)) {
696 MakeErrMsg(ErrStr, path + ": can't get status of file");
700 // Note: this check catches strange situations. In all cases, LLVM should
701 // only be involved in the creation and deletion of regular files. This
702 // check ensures that what we're trying to erase is a regular file. It
703 // effectively prevents LLVM from erasing things like /dev/null, any block
704 // special file, or other things that aren't "regular" files.
705 if (S_ISREG(buf.st_mode)) {
706 if (unlink(path.c_str()) != 0)
707 return MakeErrMsg(ErrStr, path + ": can't destroy file");
711 if (!S_ISDIR(buf.st_mode)) {
712 if (ErrStr) *ErrStr = "not a file or directory";
716 if (remove_contents) {
717 // Recursively descend the directory to remove its contents.
718 std::string cmd = "/bin/rm -rf " + path;
719 if (system(cmd.c_str()) != 0) {
720 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
726 // Otherwise, try to just remove the one directory.
727 std::string pathname(path);
728 size_t lastchar = path.length() - 1;
729 if (pathname[lastchar] == '/')
730 pathname[lastchar] = '\0';
732 pathname[lastchar+1] = '\0';
734 if (rmdir(pathname.c_str()) != 0)
735 return MakeErrMsg(ErrStr, pathname + ": can't erase directory");
740 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
741 if (0 != ::rename(path.c_str(), newName.c_str()))
742 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
743 newName.str() + "'");
748 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
750 utb.actime = si.modTime.toPosixTime();
751 utb.modtime = utb.actime;
752 if (0 != ::utime(path.c_str(),&utb))
753 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
754 if (0 != ::chmod(path.c_str(),si.mode))
755 return MakeErrMsg(ErrStr, path + ": can't set mode");
760 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
763 inFile = ::open(Src.c_str(), O_RDONLY);
765 return MakeErrMsg(ErrMsg, Src.str() +
766 ": can't open source file to copy");
768 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
771 return MakeErrMsg(ErrMsg, Dest.str() +
772 ": can't create destination file for copy");
775 char Buffer[16*1024];
776 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
778 if (errno != EINTR && errno != EAGAIN) {
781 return MakeErrMsg(ErrMsg, Src.str()+": can't read source file");
784 char *BufPtr = Buffer;
786 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
787 if (AmtWritten == -1) {
788 if (errno != EINTR && errno != EAGAIN) {
791 return MakeErrMsg(ErrMsg, Dest.str() +
792 ": can't write destination file");
796 BufPtr += AmtWritten;
807 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
809 if (reuse_current && (fs::exists(path, Exists) || !Exists))
810 return false; // File doesn't exist already, just use it!
812 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
813 // mktemp or our own implementation.
814 // This uses std::vector instead of SmallVector to avoid a dependence on
815 // libSupport. And performance isn't critical here.
816 std::vector<char> Buf;
817 Buf.resize(path.size()+8);
818 char *FNBuffer = &Buf[0];
819 path.copy(FNBuffer,path.size());
821 if (!fs::is_directory(path, isdir) && isdir)
822 strcpy(FNBuffer+path.size(), "/XXXXXX");
824 strcpy(FNBuffer+path.size(), "-XXXXXX");
826 #if defined(HAVE_MKSTEMP)
828 if ((TempFD = mkstemp(FNBuffer)) == -1)
829 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
831 // We don't need to hold the temp file descriptor... we will trust that no one
832 // will overwrite/delete the file before we can open it again.
838 // By default mkstemp sets the mode to 0600, so update mode bits now.
839 AddPermissionBits (*this, 0666);
840 #elif defined(HAVE_MKTEMP)
841 // If we don't have mkstemp, use the old and obsolete mktemp function.
842 if (mktemp(FNBuffer) == 0)
843 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
848 // Okay, looks like we have to do it all by our lonesome.
849 static unsigned FCounter = 0;
850 // Try to initialize with unique value.
851 if (FCounter == 0) FCounter = ((unsigned)getpid() & 0xFFFF) << 8;
852 char* pos = strstr(FNBuffer, "XXXXXX");
854 if (++FCounter > 0xFFFFFF) {
855 return MakeErrMsg(ErrMsg,
856 path + ": can't make unique filename: too many files");
858 sprintf(pos, "%06X", FCounter);
861 // POSSIBLE SECURITY BUG: An attacker can easily guess the name and exploit
867 const char *Path::MapInFilePages(int FD, size_t FileSize, off_t Offset) {
868 int Flags = MAP_PRIVATE;
872 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, Offset);
873 if (BasePtr == MAP_FAILED)
875 return (const char*)BasePtr;
878 void Path::UnMapFilePages(const char *BasePtr, size_t FileSize) {
879 const void *Addr = static_cast<const void *>(BasePtr);
880 ::munmap(const_cast<void *>(Addr), FileSize);
883 } // end llvm namespace