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::GetTemporaryDirectory(std::string *ErrMsg) {
129 #if defined(HAVE_MKDTEMP)
130 // The best way is with mkdtemp but that's not available on many systems,
131 // Linux and FreeBSD have it. Others probably won't.
132 char pathname[] = "/tmp/llvm_XXXXXX";
133 if (0 == mkdtemp(pathname)) {
135 std::string(pathname) + ": can't create temporary directory");
138 return Path(pathname);
139 #elif defined(HAVE_MKSTEMP)
140 // If no mkdtemp is available, mkstemp can be used to create a temporary file
141 // which is then removed and created as a directory. We prefer this over
142 // mktemp because of mktemp's inherent security and threading risks. We still
143 // have a slight race condition from the time the temporary file is created to
144 // the time it is re-created as a directoy.
145 char pathname[] = "/tmp/llvm_XXXXXX";
147 if (-1 == (fd = mkstemp(pathname))) {
149 std::string(pathname) + ": can't create temporary directory");
153 ::unlink(pathname); // start race condition, ignore errors
154 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
156 std::string(pathname) + ": can't create temporary directory");
159 return Path(pathname);
160 #elif defined(HAVE_MKTEMP)
161 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
162 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
163 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
164 // the XXXXXX with the pid of the process and a letter. That leads to only
165 // twenty six temporary files that can be generated.
166 char pathname[] = "/tmp/llvm_XXXXXX";
167 char *TmpName = ::mktemp(pathname);
170 std::string(TmpName) + ": can't create unique directory name");
173 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
175 std::string(TmpName) + ": can't create temporary directory");
178 return Path(TmpName);
180 // This is the worst case implementation. tempnam(3) leaks memory unless its
181 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
182 // issues. The mktemp(3) function doesn't have enough variability in the
183 // temporary name generated. So, we provide our own implementation that
184 // increments an integer from a random number seeded by the current time. This
185 // should be sufficiently unique that we don't have many collisions between
186 // processes. Generally LLVM processes don't run very long and don't use very
187 // many temporary files so this shouldn't be a big issue for LLVM.
188 static time_t num = ::time(0);
189 char pathname[MAXPATHLEN];
192 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
193 } while ( 0 == access(pathname, F_OK ) );
194 if (-1 == ::mkdir(pathname, S_IRWXU)) {
196 std::string(pathname) + ": can't create temporary directory");
199 return Path(pathname);
204 Path::GetCurrentDirectory() {
205 char pathname[MAXPATHLEN];
206 if (!getcwd(pathname, MAXPATHLEN)) {
207 assert(false && "Could not query current working directory.");
211 return Path(pathname);
214 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
215 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
216 defined(__linux__) || defined(__CYGWIN__)
218 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
219 const char *dir, const char *bin)
223 snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
224 if (realpath(buf, ret) == NULL)
226 if (stat(buf, &sb) != 0)
233 getprogpath(char ret[PATH_MAX], const char *bin)
235 char *pv, *s, *t, buf[PATH_MAX];
237 /* First approach: absolute path. */
239 if (test_dir(buf, ret, "/", bin) == 0)
244 /* Second approach: relative path. */
245 if (strchr(bin, '/') != NULL) {
246 if (getcwd(buf, PATH_MAX) == NULL)
248 if (test_dir(buf, ret, buf, bin) == 0)
253 /* Third approach: $PATH */
254 if ((pv = getenv("PATH")) == NULL)
259 while ((t = strsep(&s, ":")) != NULL) {
260 if (test_dir(buf, ret, t, bin) == 0) {
268 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
270 /// GetMainExecutable - Return the path to the main executable, given the
271 /// value of argv[0] from program startup.
272 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
273 #if defined(__APPLE__)
274 // On OS X the executable path is saved to the stack by dyld. Reading it
275 // from there is much faster than calling dladdr, especially for large
276 // binaries with symbols.
277 char exe_path[MAXPATHLEN];
278 uint32_t size = sizeof(exe_path);
279 if (_NSGetExecutablePath(exe_path, &size) == 0) {
280 char link_path[MAXPATHLEN];
281 if (realpath(exe_path, link_path))
282 return Path(link_path);
284 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
285 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__)
286 char exe_path[PATH_MAX];
288 if (getprogpath(exe_path, argv0) != NULL)
289 return Path(exe_path);
290 #elif defined(__linux__) || defined(__CYGWIN__)
291 char exe_path[MAXPATHLEN];
292 StringRef aPath("/proc/self/exe");
293 if (sys::fs::exists(aPath)) {
294 // /proc is not always mounted under Linux (chroot for example).
295 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
297 return Path(StringRef(exe_path, len));
299 // Fall back to the classical detection.
300 if (getprogpath(exe_path, argv0) != NULL)
301 return Path(exe_path);
303 #elif defined(HAVE_DLFCN_H)
304 // Use dladdr to get executable path if available.
306 int err = dladdr(MainAddr, &DLInfo);
310 // If the filename is a symlink, we need to resolve and return the location of
311 // the actual executable.
312 char link_path[MAXPATHLEN];
313 if (realpath(DLInfo.dli_fname, link_path))
314 return Path(link_path);
316 #error GetMainExecutable is not implemented on this host yet.
322 StringRef Path::getDirname() const {
323 return getDirnameCharSep(path, "/");
327 Path::getBasename() const {
328 // Find the last slash
329 std::string::size_type slash = path.rfind('/');
330 if (slash == std::string::npos)
335 std::string::size_type dot = path.rfind('.');
336 if (dot == std::string::npos || dot < slash)
337 return StringRef(path).substr(slash);
339 return StringRef(path).substr(slash, dot - slash);
343 Path::getSuffix() const {
344 // Find the last slash
345 std::string::size_type slash = path.rfind('/');
346 if (slash == std::string::npos)
351 std::string::size_type dot = path.rfind('.');
352 if (dot == std::string::npos || dot < slash)
355 return StringRef(path).substr(dot + 1);
358 bool Path::getMagicNumber(std::string &Magic, unsigned len) const {
359 assert(len < 1024 && "Request for magic string too long");
361 int fd = ::open(path.c_str(), O_RDONLY);
364 ssize_t bytes_read = ::read(fd, Buf, len);
366 if (ssize_t(len) != bytes_read)
368 Magic.assign(Buf, len);
373 Path::exists() const {
374 return 0 == access(path.c_str(), F_OK );
378 Path::isDirectory() const {
380 if (0 != stat(path.c_str(), &buf))
382 return ((buf.st_mode & S_IFMT) == S_IFDIR) ? true : false;
386 Path::isSymLink() const {
388 if (0 != lstat(path.c_str(), &buf))
390 return S_ISLNK(buf.st_mode);
395 Path::canRead() const {
396 return 0 == access(path.c_str(), R_OK);
400 Path::canWrite() const {
401 return 0 == access(path.c_str(), W_OK);
405 Path::isRegularFile() const {
406 // Get the status so we can determine if it's a file or directory
409 if (0 != stat(path.c_str(), &buf))
412 if (S_ISREG(buf.st_mode))
419 Path::canExecute() const {
420 if (0 != access(path.c_str(), R_OK | X_OK ))
423 if (0 != stat(path.c_str(), &buf))
425 if (!S_ISREG(buf.st_mode))
431 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
432 if (!fsIsValid || update) {
434 if (0 != stat(path.c_str(), &buf)) {
435 MakeErrMsg(ErrStr, path + ": can't get status of file");
438 status.fileSize = buf.st_size;
439 status.modTime.fromEpochTime(buf.st_mtime);
440 status.mode = buf.st_mode;
441 status.user = buf.st_uid;
442 status.group = buf.st_gid;
443 status.uniqueID = uint64_t(buf.st_ino);
444 status.isDir = S_ISDIR(buf.st_mode);
445 status.isFile = S_ISREG(buf.st_mode);
451 static bool AddPermissionBits(const Path &File, int bits) {
452 // Get the umask value from the operating system. We want to use it
453 // when changing the file's permissions. Since calling umask() sets
454 // the umask and returns its old value, we must call it a second
455 // time to reset it to the user's preference.
456 int mask = umask(0777); // The arg. to umask is arbitrary.
457 umask(mask); // Restore the umask.
459 // Get the file's current mode.
461 if (0 != stat(File.c_str(), &buf))
463 // Change the file to have whichever permissions bits from 'bits'
464 // that the umask would not disable.
465 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
470 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
471 if (!AddPermissionBits(*this, 0444))
472 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
476 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
477 if (!AddPermissionBits(*this, 0222))
478 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
482 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
483 if (!AddPermissionBits(*this, 0111))
484 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
489 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
490 DIR* direntries = ::opendir(path.c_str());
492 return MakeErrMsg(ErrMsg, path + ": can't open directory");
494 std::string dirPath = path;
495 if (!lastIsSlash(dirPath))
499 struct dirent* de = ::readdir(direntries);
500 for ( ; de != 0; de = ::readdir(direntries)) {
501 if (de->d_name[0] != '.') {
502 Path aPath(dirPath + (const char*)de->d_name);
504 if (0 != lstat(aPath.path.c_str(), &st)) {
505 if (S_ISLNK(st.st_mode))
506 continue; // dangling symlink -- ignore
507 return MakeErrMsg(ErrMsg,
508 aPath.path + ": can't determine file object type");
510 result.insert(aPath);
514 closedir(direntries);
519 Path::set(StringRef a_path) {
527 Path::appendComponent(StringRef name) {
530 if (!lastIsSlash(path))
537 Path::eraseComponent() {
538 size_t slashpos = path.rfind('/',path.size());
539 if (slashpos == 0 || slashpos == std::string::npos) {
543 if (slashpos == path.size() - 1)
544 slashpos = path.rfind('/',slashpos-1);
545 if (slashpos == std::string::npos) {
549 path.erase(slashpos);
554 Path::eraseSuffix() {
555 size_t dotpos = path.rfind('.',path.size());
556 size_t slashpos = path.rfind('/',path.size());
557 if (dotpos != std::string::npos) {
558 if (slashpos == std::string::npos || dotpos > slashpos+1) {
559 path.erase(dotpos, path.size()-dotpos);
566 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
568 if (access(beg, R_OK | W_OK) == 0)
571 if (create_parents) {
575 for (; c != beg; --c)
578 // Recurse to handling the parent directory.
580 bool x = createDirectoryHelper(beg, c, create_parents);
583 // Return if we encountered an error.
591 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
595 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
596 // Get a writeable copy of the path name
597 std::string pathname(path);
599 // Null-terminate the last component
600 size_t lastchar = path.length() - 1 ;
602 if (pathname[lastchar] != '/')
605 pathname[lastchar] = '\0';
607 if (createDirectoryHelper(&pathname[0], &pathname[lastchar], create_parents))
608 return MakeErrMsg(ErrMsg, pathname + ": can't create directory");
614 Path::createFileOnDisk(std::string* ErrMsg) {
616 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
618 return MakeErrMsg(ErrMsg, path + ": can't create file");
624 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
625 // Make this into a unique file name
626 if (makeUnique( reuse_current, ErrMsg ))
630 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
632 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
638 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
639 // Get the status so we can determine if it's a file or directory.
641 if (0 != stat(path.c_str(), &buf)) {
642 MakeErrMsg(ErrStr, path + ": can't get status of file");
646 // Note: this check catches strange situations. In all cases, LLVM should
647 // only be involved in the creation and deletion of regular files. This
648 // check ensures that what we're trying to erase is a regular file. It
649 // effectively prevents LLVM from erasing things like /dev/null, any block
650 // special file, or other things that aren't "regular" files.
651 if (S_ISREG(buf.st_mode)) {
652 if (unlink(path.c_str()) != 0)
653 return MakeErrMsg(ErrStr, path + ": can't destroy file");
657 if (!S_ISDIR(buf.st_mode)) {
658 if (ErrStr) *ErrStr = "not a file or directory";
662 if (remove_contents) {
663 // Recursively descend the directory to remove its contents.
664 std::string cmd = "/bin/rm -rf " + path;
665 if (system(cmd.c_str()) != 0) {
666 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
672 // Otherwise, try to just remove the one directory.
673 std::string pathname(path);
674 size_t lastchar = path.length() - 1;
675 if (pathname[lastchar] == '/')
676 pathname[lastchar] = '\0';
678 pathname[lastchar+1] = '\0';
680 if (rmdir(pathname.c_str()) != 0)
681 return MakeErrMsg(ErrStr, pathname + ": can't erase directory");
686 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
687 if (0 != ::rename(path.c_str(), newName.c_str()))
688 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
689 newName.str() + "'");
694 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
696 utb.actime = si.modTime.toPosixTime();
697 utb.modtime = utb.actime;
698 if (0 != ::utime(path.c_str(),&utb))
699 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
700 if (0 != ::chmod(path.c_str(),si.mode))
701 return MakeErrMsg(ErrStr, path + ": can't set mode");
706 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
709 inFile = ::open(Src.c_str(), O_RDONLY);
711 return MakeErrMsg(ErrMsg, Src.str() +
712 ": can't open source file to copy");
714 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
717 return MakeErrMsg(ErrMsg, Dest.str() +
718 ": can't create destination file for copy");
721 char Buffer[16*1024];
722 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
724 if (errno != EINTR && errno != EAGAIN) {
727 return MakeErrMsg(ErrMsg, Src.str()+": can't read source file");
730 char *BufPtr = Buffer;
732 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
733 if (AmtWritten == -1) {
734 if (errno != EINTR && errno != EAGAIN) {
737 return MakeErrMsg(ErrMsg, Dest.str() +
738 ": can't write destination file");
742 BufPtr += AmtWritten;
753 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
755 if (reuse_current && (fs::exists(path, Exists) || !Exists))
756 return false; // File doesn't exist already, just use it!
758 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
759 // mktemp or our own implementation.
760 // This uses std::vector instead of SmallVector to avoid a dependence on
761 // libSupport. And performance isn't critical here.
762 std::vector<char> Buf;
763 Buf.resize(path.size()+8);
764 char *FNBuffer = &Buf[0];
765 path.copy(FNBuffer,path.size());
767 if (!fs::is_directory(path, isdir) && isdir)
768 strcpy(FNBuffer+path.size(), "/XXXXXX");
770 strcpy(FNBuffer+path.size(), "-XXXXXX");
772 #if defined(HAVE_MKSTEMP)
774 if ((TempFD = mkstemp(FNBuffer)) == -1)
775 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
777 // We don't need to hold the temp file descriptor... we will trust that no one
778 // will overwrite/delete the file before we can open it again.
784 // By default mkstemp sets the mode to 0600, so update mode bits now.
785 AddPermissionBits (*this, 0666);
786 #elif defined(HAVE_MKTEMP)
787 // If we don't have mkstemp, use the old and obsolete mktemp function.
788 if (mktemp(FNBuffer) == 0)
789 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
794 // Okay, looks like we have to do it all by our lonesome.
795 static unsigned FCounter = 0;
796 // Try to initialize with unique value.
797 if (FCounter == 0) FCounter = ((unsigned)getpid() & 0xFFFF) << 8;
798 char* pos = strstr(FNBuffer, "XXXXXX");
800 if (++FCounter > 0xFFFFFF) {
801 return MakeErrMsg(ErrMsg,
802 path + ": can't make unique filename: too many files");
804 sprintf(pos, "%06X", FCounter);
807 // POSSIBLE SECURITY BUG: An attacker can easily guess the name and exploit
813 const char *Path::MapInFilePages(int FD, size_t FileSize, off_t Offset) {
814 int Flags = MAP_PRIVATE;
818 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, Offset);
819 if (BasePtr == MAP_FAILED)
821 return (const char*)BasePtr;
824 void Path::UnMapFilePages(const char *BasePtr, size_t FileSize) {
825 const void *Addr = static_cast<const void *>(BasePtr);
826 ::munmap(const_cast<void *>(Addr), FileSize);
829 } // end llvm namespace