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::GetTemporaryDirectory(std::string *ErrMsg) {
122 #if defined(HAVE_MKDTEMP)
123 // The best way is with mkdtemp but that's not available on many systems,
124 // Linux and FreeBSD have it. Others probably won't.
125 char pathname[] = "/tmp/llvm_XXXXXX";
126 if (0 == mkdtemp(pathname)) {
128 std::string(pathname) + ": can't create temporary directory");
131 return Path(pathname);
132 #elif defined(HAVE_MKSTEMP)
133 // If no mkdtemp is available, mkstemp can be used to create a temporary file
134 // which is then removed and created as a directory. We prefer this over
135 // mktemp because of mktemp's inherent security and threading risks. We still
136 // have a slight race condition from the time the temporary file is created to
137 // the time it is re-created as a directoy.
138 char pathname[] = "/tmp/llvm_XXXXXX";
140 if (-1 == (fd = mkstemp(pathname))) {
142 std::string(pathname) + ": can't create temporary directory");
146 ::unlink(pathname); // start race condition, ignore errors
147 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
149 std::string(pathname) + ": can't create temporary directory");
152 return Path(pathname);
153 #elif defined(HAVE_MKTEMP)
154 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
155 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
156 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
157 // the XXXXXX with the pid of the process and a letter. That leads to only
158 // twenty six temporary files that can be generated.
159 char pathname[] = "/tmp/llvm_XXXXXX";
160 char *TmpName = ::mktemp(pathname);
163 std::string(TmpName) + ": can't create unique directory name");
166 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
168 std::string(TmpName) + ": can't create temporary directory");
171 return Path(TmpName);
173 // This is the worst case implementation. tempnam(3) leaks memory unless its
174 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
175 // issues. The mktemp(3) function doesn't have enough variability in the
176 // temporary name generated. So, we provide our own implementation that
177 // increments an integer from a random number seeded by the current time. This
178 // should be sufficiently unique that we don't have many collisions between
179 // processes. Generally LLVM processes don't run very long and don't use very
180 // many temporary files so this shouldn't be a big issue for LLVM.
181 static time_t num = ::time(0);
182 char pathname[MAXPATHLEN];
185 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
186 } while ( 0 == access(pathname, F_OK ) );
187 if (-1 == ::mkdir(pathname, S_IRWXU)) {
189 std::string(pathname) + ": can't create temporary directory");
192 return Path(pathname);
197 Path::GetCurrentDirectory() {
198 char pathname[MAXPATHLEN];
199 if (!getcwd(pathname, MAXPATHLEN)) {
200 assert(false && "Could not query current working directory.");
204 return Path(pathname);
207 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
208 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
209 defined(__linux__) || defined(__CYGWIN__)
211 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
212 const char *dir, const char *bin)
216 snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
217 if (realpath(buf, ret) == NULL)
219 if (stat(buf, &sb) != 0)
226 getprogpath(char ret[PATH_MAX], const char *bin)
228 char *pv, *s, *t, buf[PATH_MAX];
230 /* First approach: absolute path. */
232 if (test_dir(buf, ret, "/", bin) == 0)
237 /* Second approach: relative path. */
238 if (strchr(bin, '/') != NULL) {
239 if (getcwd(buf, PATH_MAX) == NULL)
241 if (test_dir(buf, ret, buf, bin) == 0)
246 /* Third approach: $PATH */
247 if ((pv = getenv("PATH")) == NULL)
252 while ((t = strsep(&s, ":")) != NULL) {
253 if (test_dir(buf, ret, t, bin) == 0) {
261 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
263 /// GetMainExecutable - Return the path to the main executable, given the
264 /// value of argv[0] from program startup.
265 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
266 #if defined(__APPLE__)
267 // On OS X the executable path is saved to the stack by dyld. Reading it
268 // from there is much faster than calling dladdr, especially for large
269 // binaries with symbols.
270 char exe_path[MAXPATHLEN];
271 uint32_t size = sizeof(exe_path);
272 if (_NSGetExecutablePath(exe_path, &size) == 0) {
273 char link_path[MAXPATHLEN];
274 if (realpath(exe_path, link_path))
275 return Path(link_path);
277 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
278 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__)
279 char exe_path[PATH_MAX];
281 if (getprogpath(exe_path, argv0) != NULL)
282 return Path(exe_path);
283 #elif defined(__linux__) || defined(__CYGWIN__)
284 char exe_path[MAXPATHLEN];
285 StringRef aPath("/proc/self/exe");
286 if (sys::fs::exists(aPath)) {
287 // /proc is not always mounted under Linux (chroot for example).
288 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
290 return Path(StringRef(exe_path, len));
292 // Fall back to the classical detection.
293 if (getprogpath(exe_path, argv0) != NULL)
294 return Path(exe_path);
296 #elif defined(HAVE_DLFCN_H)
297 // Use dladdr to get executable path if available.
299 int err = dladdr(MainAddr, &DLInfo);
303 // If the filename is a symlink, we need to resolve and return the location of
304 // the actual executable.
305 char link_path[MAXPATHLEN];
306 if (realpath(DLInfo.dli_fname, link_path))
307 return Path(link_path);
309 #error GetMainExecutable is not implemented on this host yet.
314 bool Path::getMagicNumber(std::string &Magic, unsigned len) const {
315 assert(len < 1024 && "Request for magic string too long");
317 int fd = ::open(path.c_str(), O_RDONLY);
320 ssize_t bytes_read = ::read(fd, Buf, len);
322 if (ssize_t(len) != bytes_read)
324 Magic.assign(Buf, len);
329 Path::exists() const {
330 return 0 == access(path.c_str(), F_OK );
334 Path::isDirectory() const {
336 if (0 != stat(path.c_str(), &buf))
338 return ((buf.st_mode & S_IFMT) == S_IFDIR) ? true : false;
342 Path::isSymLink() const {
344 if (0 != lstat(path.c_str(), &buf))
346 return S_ISLNK(buf.st_mode);
351 Path::canRead() const {
352 return 0 == access(path.c_str(), R_OK);
356 Path::canWrite() const {
357 return 0 == access(path.c_str(), W_OK);
361 Path::isRegularFile() const {
362 // Get the status so we can determine if it's a file or directory
365 if (0 != stat(path.c_str(), &buf))
368 if (S_ISREG(buf.st_mode))
375 Path::canExecute() const {
376 if (0 != access(path.c_str(), R_OK | X_OK ))
379 if (0 != stat(path.c_str(), &buf))
381 if (!S_ISREG(buf.st_mode))
387 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
388 if (!fsIsValid || update) {
390 if (0 != stat(path.c_str(), &buf)) {
391 MakeErrMsg(ErrStr, path + ": can't get status of file");
394 status.fileSize = buf.st_size;
395 status.modTime.fromEpochTime(buf.st_mtime);
396 status.mode = buf.st_mode;
397 status.user = buf.st_uid;
398 status.group = buf.st_gid;
399 status.uniqueID = uint64_t(buf.st_ino);
400 status.isDir = S_ISDIR(buf.st_mode);
401 status.isFile = S_ISREG(buf.st_mode);
407 static bool AddPermissionBits(const Path &File, int bits) {
408 // Get the umask value from the operating system. We want to use it
409 // when changing the file's permissions. Since calling umask() sets
410 // the umask and returns its old value, we must call it a second
411 // time to reset it to the user's preference.
412 int mask = umask(0777); // The arg. to umask is arbitrary.
413 umask(mask); // Restore the umask.
415 // Get the file's current mode.
417 if (0 != stat(File.c_str(), &buf))
419 // Change the file to have whichever permissions bits from 'bits'
420 // that the umask would not disable.
421 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
426 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
427 if (!AddPermissionBits(*this, 0444))
428 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
432 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
433 if (!AddPermissionBits(*this, 0222))
434 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
439 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
440 DIR* direntries = ::opendir(path.c_str());
442 return MakeErrMsg(ErrMsg, path + ": can't open directory");
444 std::string dirPath = path;
445 if (!lastIsSlash(dirPath))
449 struct dirent* de = ::readdir(direntries);
450 for ( ; de != 0; de = ::readdir(direntries)) {
451 if (de->d_name[0] != '.') {
452 Path aPath(dirPath + (const char*)de->d_name);
454 if (0 != lstat(aPath.path.c_str(), &st)) {
455 if (S_ISLNK(st.st_mode))
456 continue; // dangling symlink -- ignore
457 return MakeErrMsg(ErrMsg,
458 aPath.path + ": can't determine file object type");
460 result.insert(aPath);
464 closedir(direntries);
469 Path::set(StringRef a_path) {
477 Path::appendComponent(StringRef name) {
480 if (!lastIsSlash(path))
487 Path::eraseComponent() {
488 size_t slashpos = path.rfind('/',path.size());
489 if (slashpos == 0 || slashpos == std::string::npos) {
493 if (slashpos == path.size() - 1)
494 slashpos = path.rfind('/',slashpos-1);
495 if (slashpos == std::string::npos) {
499 path.erase(slashpos);
504 Path::eraseSuffix() {
505 size_t dotpos = path.rfind('.',path.size());
506 size_t slashpos = path.rfind('/',path.size());
507 if (dotpos != std::string::npos) {
508 if (slashpos == std::string::npos || dotpos > slashpos+1) {
509 path.erase(dotpos, path.size()-dotpos);
516 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
518 if (access(beg, R_OK | W_OK) == 0)
521 if (create_parents) {
525 for (; c != beg; --c)
528 // Recurse to handling the parent directory.
530 bool x = createDirectoryHelper(beg, c, create_parents);
533 // Return if we encountered an error.
541 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
545 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
546 // Get a writeable copy of the path name
547 std::string pathname(path);
549 // Null-terminate the last component
550 size_t lastchar = path.length() - 1 ;
552 if (pathname[lastchar] != '/')
555 pathname[lastchar] = '\0';
557 if (createDirectoryHelper(&pathname[0], &pathname[lastchar], create_parents))
558 return MakeErrMsg(ErrMsg, pathname + ": can't create directory");
564 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
565 // Make this into a unique file name
566 if (makeUnique( reuse_current, ErrMsg ))
570 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
572 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
578 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
579 // Get the status so we can determine if it's a file or directory.
581 if (0 != stat(path.c_str(), &buf)) {
582 MakeErrMsg(ErrStr, path + ": can't get status of file");
586 // Note: this check catches strange situations. In all cases, LLVM should
587 // only be involved in the creation and deletion of regular files. This
588 // check ensures that what we're trying to erase is a regular file. It
589 // effectively prevents LLVM from erasing things like /dev/null, any block
590 // special file, or other things that aren't "regular" files.
591 if (S_ISREG(buf.st_mode)) {
592 if (unlink(path.c_str()) != 0)
593 return MakeErrMsg(ErrStr, path + ": can't destroy file");
597 if (!S_ISDIR(buf.st_mode)) {
598 if (ErrStr) *ErrStr = "not a file or directory";
602 if (remove_contents) {
603 // Recursively descend the directory to remove its contents.
604 std::string cmd = "/bin/rm -rf " + path;
605 if (system(cmd.c_str()) != 0) {
606 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
612 // Otherwise, try to just remove the one directory.
613 std::string pathname(path);
614 size_t lastchar = path.length() - 1;
615 if (pathname[lastchar] == '/')
616 pathname[lastchar] = '\0';
618 pathname[lastchar+1] = '\0';
620 if (rmdir(pathname.c_str()) != 0)
621 return MakeErrMsg(ErrStr, pathname + ": can't erase directory");
626 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
627 if (0 != ::rename(path.c_str(), newName.c_str()))
628 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
629 newName.str() + "'");
634 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
636 utb.actime = si.modTime.toPosixTime();
637 utb.modtime = utb.actime;
638 if (0 != ::utime(path.c_str(),&utb))
639 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
640 if (0 != ::chmod(path.c_str(),si.mode))
641 return MakeErrMsg(ErrStr, path + ": can't set mode");
646 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
648 if (reuse_current && (fs::exists(path, Exists) || !Exists))
649 return false; // File doesn't exist already, just use it!
651 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
652 // mktemp or our own implementation.
653 // This uses std::vector instead of SmallVector to avoid a dependence on
654 // libSupport. And performance isn't critical here.
655 std::vector<char> Buf;
656 Buf.resize(path.size()+8);
657 char *FNBuffer = &Buf[0];
658 path.copy(FNBuffer,path.size());
660 if (!fs::is_directory(path, isdir) && isdir)
661 strcpy(FNBuffer+path.size(), "/XXXXXX");
663 strcpy(FNBuffer+path.size(), "-XXXXXX");
665 #if defined(HAVE_MKSTEMP)
667 if ((TempFD = mkstemp(FNBuffer)) == -1)
668 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
670 // We don't need to hold the temp file descriptor... we will trust that no one
671 // will overwrite/delete the file before we can open it again.
677 // By default mkstemp sets the mode to 0600, so update mode bits now.
678 AddPermissionBits (*this, 0666);
679 #elif defined(HAVE_MKTEMP)
680 // If we don't have mkstemp, use the old and obsolete mktemp function.
681 if (mktemp(FNBuffer) == 0)
682 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
687 // Okay, looks like we have to do it all by our lonesome.
688 static unsigned FCounter = 0;
689 // Try to initialize with unique value.
690 if (FCounter == 0) FCounter = ((unsigned)getpid() & 0xFFFF) << 8;
691 char* pos = strstr(FNBuffer, "XXXXXX");
693 if (++FCounter > 0xFFFFFF) {
694 return MakeErrMsg(ErrMsg,
695 path + ": can't make unique filename: too many files");
697 sprintf(pos, "%06X", FCounter);
700 // POSSIBLE SECURITY BUG: An attacker can easily guess the name and exploit
705 } // end llvm namespace