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::GetTemporaryDirectory(std::string *ErrMsg) {
114 #if defined(HAVE_MKDTEMP)
115 // The best way is with mkdtemp but that's not available on many systems,
116 // Linux and FreeBSD have it. Others probably won't.
117 char pathname[] = "/tmp/llvm_XXXXXX";
118 if (0 == mkdtemp(pathname)) {
120 std::string(pathname) + ": can't create temporary directory");
123 return Path(pathname);
124 #elif defined(HAVE_MKSTEMP)
125 // If no mkdtemp is available, mkstemp can be used to create a temporary file
126 // which is then removed and created as a directory. We prefer this over
127 // mktemp because of mktemp's inherent security and threading risks. We still
128 // have a slight race condition from the time the temporary file is created to
129 // the time it is re-created as a directoy.
130 char pathname[] = "/tmp/llvm_XXXXXX";
132 if (-1 == (fd = mkstemp(pathname))) {
134 std::string(pathname) + ": can't create temporary directory");
138 ::unlink(pathname); // start race condition, ignore errors
139 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
141 std::string(pathname) + ": can't create temporary directory");
144 return Path(pathname);
145 #elif defined(HAVE_MKTEMP)
146 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
147 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
148 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
149 // the XXXXXX with the pid of the process and a letter. That leads to only
150 // twenty six temporary files that can be generated.
151 char pathname[] = "/tmp/llvm_XXXXXX";
152 char *TmpName = ::mktemp(pathname);
155 std::string(TmpName) + ": can't create unique directory name");
158 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
160 std::string(TmpName) + ": can't create temporary directory");
163 return Path(TmpName);
165 // This is the worst case implementation. tempnam(3) leaks memory unless its
166 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
167 // issues. The mktemp(3) function doesn't have enough variability in the
168 // temporary name generated. So, we provide our own implementation that
169 // increments an integer from a random number seeded by the current time. This
170 // should be sufficiently unique that we don't have many collisions between
171 // processes. Generally LLVM processes don't run very long and don't use very
172 // many temporary files so this shouldn't be a big issue for LLVM.
173 static time_t num = ::time(0);
174 char pathname[MAXPATHLEN];
177 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
178 } while ( 0 == access(pathname, F_OK ) );
179 if (-1 == ::mkdir(pathname, S_IRWXU)) {
181 std::string(pathname) + ": can't create temporary directory");
184 return Path(pathname);
189 Path::GetCurrentDirectory() {
190 char pathname[MAXPATHLEN];
191 if (!getcwd(pathname, MAXPATHLEN)) {
192 assert(false && "Could not query current working directory.");
196 return Path(pathname);
199 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
200 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
201 defined(__linux__) || defined(__CYGWIN__)
203 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
204 const char *dir, const char *bin)
208 snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
209 if (realpath(buf, ret) == NULL)
211 if (stat(buf, &sb) != 0)
218 getprogpath(char ret[PATH_MAX], const char *bin)
220 char *pv, *s, *t, buf[PATH_MAX];
222 /* First approach: absolute path. */
224 if (test_dir(buf, ret, "/", bin) == 0)
229 /* Second approach: relative path. */
230 if (strchr(bin, '/') != NULL) {
231 if (getcwd(buf, PATH_MAX) == NULL)
233 if (test_dir(buf, ret, buf, bin) == 0)
238 /* Third approach: $PATH */
239 if ((pv = getenv("PATH")) == NULL)
244 while ((t = strsep(&s, ":")) != NULL) {
245 if (test_dir(buf, ret, t, bin) == 0) {
253 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
255 /// GetMainExecutable - Return the path to the main executable, given the
256 /// value of argv[0] from program startup.
257 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
258 #if defined(__APPLE__)
259 // On OS X the executable path is saved to the stack by dyld. Reading it
260 // from there is much faster than calling dladdr, especially for large
261 // binaries with symbols.
262 char exe_path[MAXPATHLEN];
263 uint32_t size = sizeof(exe_path);
264 if (_NSGetExecutablePath(exe_path, &size) == 0) {
265 char link_path[MAXPATHLEN];
266 if (realpath(exe_path, link_path))
267 return Path(link_path);
269 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
270 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__)
271 char exe_path[PATH_MAX];
273 if (getprogpath(exe_path, argv0) != NULL)
274 return Path(exe_path);
275 #elif defined(__linux__) || defined(__CYGWIN__)
276 char exe_path[MAXPATHLEN];
277 StringRef aPath("/proc/self/exe");
278 if (sys::fs::exists(aPath)) {
279 // /proc is not always mounted under Linux (chroot for example).
280 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
282 return Path(StringRef(exe_path, len));
284 // Fall back to the classical detection.
285 if (getprogpath(exe_path, argv0) != NULL)
286 return Path(exe_path);
288 #elif defined(HAVE_DLFCN_H)
289 // Use dladdr to get executable path if available.
291 int err = dladdr(MainAddr, &DLInfo);
295 // If the filename is a symlink, we need to resolve and return the location of
296 // the actual executable.
297 char link_path[MAXPATHLEN];
298 if (realpath(DLInfo.dli_fname, link_path))
299 return Path(link_path);
301 #error GetMainExecutable is not implemented on this host yet.
307 Path::exists() const {
308 return 0 == access(path.c_str(), F_OK );
312 Path::isDirectory() const {
314 if (0 != stat(path.c_str(), &buf))
316 return ((buf.st_mode & S_IFMT) == S_IFDIR) ? true : false;
320 Path::isSymLink() const {
322 if (0 != lstat(path.c_str(), &buf))
324 return S_ISLNK(buf.st_mode);
329 Path::canRead() const {
330 return 0 == access(path.c_str(), R_OK);
334 Path::canWrite() const {
335 return 0 == access(path.c_str(), W_OK);
339 Path::isRegularFile() const {
340 // Get the status so we can determine if it's a file or directory
343 if (0 != stat(path.c_str(), &buf))
346 if (S_ISREG(buf.st_mode))
353 Path::canExecute() const {
354 if (0 != access(path.c_str(), R_OK | X_OK ))
357 if (0 != stat(path.c_str(), &buf))
359 if (!S_ISREG(buf.st_mode))
365 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
366 if (!fsIsValid || update) {
368 if (0 != stat(path.c_str(), &buf)) {
369 MakeErrMsg(ErrStr, path + ": can't get status of file");
372 status.fileSize = buf.st_size;
373 status.modTime.fromEpochTime(buf.st_mtime);
374 status.mode = buf.st_mode;
375 status.user = buf.st_uid;
376 status.group = buf.st_gid;
377 status.uniqueID = uint64_t(buf.st_ino);
378 status.isDir = S_ISDIR(buf.st_mode);
379 status.isFile = S_ISREG(buf.st_mode);
385 static bool AddPermissionBits(const Path &File, int bits) {
386 // Get the umask value from the operating system. We want to use it
387 // when changing the file's permissions. Since calling umask() sets
388 // the umask and returns its old value, we must call it a second
389 // time to reset it to the user's preference.
390 int mask = umask(0777); // The arg. to umask is arbitrary.
391 umask(mask); // Restore the umask.
393 // Get the file's current mode.
395 if (0 != stat(File.c_str(), &buf))
397 // Change the file to have whichever permissions bits from 'bits'
398 // that the umask would not disable.
399 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
404 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
405 if (!AddPermissionBits(*this, 0444))
406 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
410 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
411 if (!AddPermissionBits(*this, 0222))
412 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
417 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
418 DIR* direntries = ::opendir(path.c_str());
420 return MakeErrMsg(ErrMsg, path + ": can't open directory");
422 std::string dirPath = path;
423 if (!lastIsSlash(dirPath))
427 struct dirent* de = ::readdir(direntries);
428 for ( ; de != 0; de = ::readdir(direntries)) {
429 if (de->d_name[0] != '.') {
430 Path aPath(dirPath + (const char*)de->d_name);
432 if (0 != lstat(aPath.path.c_str(), &st)) {
433 if (S_ISLNK(st.st_mode))
434 continue; // dangling symlink -- ignore
435 return MakeErrMsg(ErrMsg,
436 aPath.path + ": can't determine file object type");
438 result.insert(aPath);
442 closedir(direntries);
447 Path::set(StringRef a_path) {
455 Path::appendComponent(StringRef name) {
458 if (!lastIsSlash(path))
465 Path::eraseComponent() {
466 size_t slashpos = path.rfind('/',path.size());
467 if (slashpos == 0 || slashpos == std::string::npos) {
471 if (slashpos == path.size() - 1)
472 slashpos = path.rfind('/',slashpos-1);
473 if (slashpos == std::string::npos) {
477 path.erase(slashpos);
482 Path::eraseSuffix() {
483 size_t dotpos = path.rfind('.',path.size());
484 size_t slashpos = path.rfind('/',path.size());
485 if (dotpos != std::string::npos) {
486 if (slashpos == std::string::npos || dotpos > slashpos+1) {
487 path.erase(dotpos, path.size()-dotpos);
494 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
496 if (access(beg, R_OK | W_OK) == 0)
499 if (create_parents) {
503 for (; c != beg; --c)
506 // Recurse to handling the parent directory.
508 bool x = createDirectoryHelper(beg, c, create_parents);
511 // Return if we encountered an error.
519 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
523 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
524 // Get a writeable copy of the path name
525 std::string pathname(path);
527 // Null-terminate the last component
528 size_t lastchar = path.length() - 1 ;
530 if (pathname[lastchar] != '/')
533 pathname[lastchar] = '\0';
535 if (createDirectoryHelper(&pathname[0], &pathname[lastchar], create_parents))
536 return MakeErrMsg(ErrMsg, pathname + ": can't create directory");
542 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
543 // Make this into a unique file name
544 if (makeUnique( reuse_current, ErrMsg ))
548 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
550 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
556 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
557 // Get the status so we can determine if it's a file or directory.
559 if (0 != stat(path.c_str(), &buf)) {
560 MakeErrMsg(ErrStr, path + ": can't get status of file");
564 // Note: this check catches strange situations. In all cases, LLVM should
565 // only be involved in the creation and deletion of regular files. This
566 // check ensures that what we're trying to erase is a regular file. It
567 // effectively prevents LLVM from erasing things like /dev/null, any block
568 // special file, or other things that aren't "regular" files.
569 if (S_ISREG(buf.st_mode)) {
570 if (unlink(path.c_str()) != 0)
571 return MakeErrMsg(ErrStr, path + ": can't destroy file");
575 if (!S_ISDIR(buf.st_mode)) {
576 if (ErrStr) *ErrStr = "not a file or directory";
580 if (remove_contents) {
581 // Recursively descend the directory to remove its contents.
582 std::string cmd = "/bin/rm -rf " + path;
583 if (system(cmd.c_str()) != 0) {
584 MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
590 // Otherwise, try to just remove the one directory.
591 std::string pathname(path);
592 size_t lastchar = path.length() - 1;
593 if (pathname[lastchar] == '/')
594 pathname[lastchar] = '\0';
596 pathname[lastchar+1] = '\0';
598 if (rmdir(pathname.c_str()) != 0)
599 return MakeErrMsg(ErrStr, pathname + ": can't erase directory");
604 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
605 if (0 != ::rename(path.c_str(), newName.c_str()))
606 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
607 newName.str() + "'");
612 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
614 utb.actime = si.modTime.toPosixTime();
615 utb.modtime = utb.actime;
616 if (0 != ::utime(path.c_str(),&utb))
617 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
618 if (0 != ::chmod(path.c_str(),si.mode))
619 return MakeErrMsg(ErrStr, path + ": can't set mode");
624 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
626 if (reuse_current && (fs::exists(path, Exists) || !Exists))
627 return false; // File doesn't exist already, just use it!
629 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
630 // mktemp or our own implementation.
631 // This uses std::vector instead of SmallVector to avoid a dependence on
632 // libSupport. And performance isn't critical here.
633 std::vector<char> Buf;
634 Buf.resize(path.size()+8);
635 char *FNBuffer = &Buf[0];
636 path.copy(FNBuffer,path.size());
638 if (!fs::is_directory(path, isdir) && isdir)
639 strcpy(FNBuffer+path.size(), "/XXXXXX");
641 strcpy(FNBuffer+path.size(), "-XXXXXX");
643 #if defined(HAVE_MKSTEMP)
645 if ((TempFD = mkstemp(FNBuffer)) == -1)
646 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
648 // We don't need to hold the temp file descriptor... we will trust that no one
649 // will overwrite/delete the file before we can open it again.
655 // By default mkstemp sets the mode to 0600, so update mode bits now.
656 AddPermissionBits (*this, 0666);
657 #elif defined(HAVE_MKTEMP)
658 // If we don't have mkstemp, use the old and obsolete mktemp function.
659 if (mktemp(FNBuffer) == 0)
660 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
665 // Okay, looks like we have to do it all by our lonesome.
666 static unsigned FCounter = 0;
667 // Try to initialize with unique value.
668 if (FCounter == 0) FCounter = ((unsigned)getpid() & 0xFFFF) << 8;
669 char* pos = strstr(FNBuffer, "XXXXXX");
671 if (++FCounter > 0xFFFFFF) {
672 return MakeErrMsg(ErrMsg,
673 path + ": can't make unique filename: too many files");
675 sprintf(pos, "%06X", FCounter);
678 // POSSIBLE SECURITY BUG: An attacker can easily guess the name and exploit
683 } // end llvm namespace