1 //===- llvm/System/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 //===----------------------------------------------------------------------===//
19 #include "llvm/Config/alloca.h"
27 #ifdef HAVE_SYS_MMAN_H
30 #ifdef HAVE_SYS_STAT_H
41 # define NAMLEN(dirent) strlen((dirent)->d_name)
43 # define dirent direct
44 # define NAMLEN(dirent) (dirent)->d_namlen
46 # include <sys/ndir.h>
60 // Put in a hack for Cygwin which falsely reports that the mkdtemp function
61 // is available when it is not.
67 inline bool lastIsSlash(const std::string& path) {
68 return !path.empty() && path[path.length() - 1] == '/';
76 extern const char sys::PathSeparator = ':';
78 Path::Path(const std::string& p)
81 Path::Path(const char *StrStart, unsigned StrLen)
82 : path(StrStart, StrLen) {}
85 Path::isValid() const {
86 // Check some obvious things
89 else if (path.length() >= MAXPATHLEN)
92 // Check that the characters are ascii chars
93 size_t len = path.length();
95 while (i < len && isascii(path[i]))
101 Path::isAbsolute() const {
104 return path[0] == '/';
107 Path::GetRootDirectory() {
114 Path::GetTemporaryDirectory(std::string* ErrMsg ) {
115 #if defined(HAVE_MKDTEMP)
116 // The best way is with mkdtemp but that's not available on many systems,
117 // Linux and FreeBSD have it. Others probably won't.
118 char pathname[MAXPATHLEN];
119 strcpy(pathname,"/tmp/llvm_XXXXXX");
120 if (0 == mkdtemp(pathname)) {
122 std::string(pathname) + ": can't create temporary directory");
126 result.set(pathname);
127 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
129 #elif defined(HAVE_MKSTEMP)
130 // If no mkdtemp is available, mkstemp can be used to create a temporary file
131 // which is then removed and created as a directory. We prefer this over
132 // mktemp because of mktemp's inherent security and threading risks. We still
133 // have a slight race condition from the time the temporary file is created to
134 // the time it is re-created as a directoy.
135 char pathname[MAXPATHLEN];
136 strcpy(pathname, "/tmp/llvm_XXXXXX");
138 if (-1 == (fd = mkstemp(pathname))) {
140 std::string(pathname) + ": can't create temporary directory");
144 ::unlink(pathname); // start race condition, ignore errors
145 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
147 std::string(pathname) + ": can't create temporary directory");
151 result.set(pathname);
152 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
154 #elif defined(HAVE_MKTEMP)
155 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
156 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
157 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
158 // the XXXXXX with the pid of the process and a letter. That leads to only
159 // twenty six temporary files that can be generated.
160 char pathname[MAXPATHLEN];
161 strcpy(pathname, "/tmp/llvm_XXXXXX");
162 char *TmpName = ::mktemp(pathname);
165 std::string(TmpName) + ": can't create unique directory name");
168 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
170 std::string(TmpName) + ": can't create temporary directory");
175 assert(result.isValid() && "mktemp didn't create a valid pathname!");
178 // This is the worst case implementation. tempnam(3) leaks memory unless its
179 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
180 // issues. The mktemp(3) function doesn't have enough variability in the
181 // temporary name generated. So, we provide our own implementation that
182 // increments an integer from a random number seeded by the current time. This
183 // should be sufficiently unique that we don't have many collisions between
184 // processes. Generally LLVM processes don't run very long and don't use very
185 // many temporary files so this shouldn't be a big issue for LLVM.
186 static time_t num = ::time(0);
187 char pathname[MAXPATHLEN];
190 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
191 } while ( 0 == access(pathname, F_OK ) );
192 if (-1 == ::mkdir(pathname, S_IRWXU)) {
194 std::string(pathname) + ": can't create temporary directory");
198 result.set(pathname);
199 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
205 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
206 #ifdef LTDL_SHLIBPATH_VAR
207 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
209 getPathList(env_var,Paths);
212 // FIXME: Should this look at LD_LIBRARY_PATH too?
213 Paths.push_back(sys::Path("/usr/local/lib/"));
214 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
215 Paths.push_back(sys::Path("/usr/lib/"));
216 Paths.push_back(sys::Path("/lib/"));
220 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
221 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
223 getPathList(env_var,Paths);
228 if (tmpPath.set(LLVM_LIBDIR))
229 if (tmpPath.canRead())
230 Paths.push_back(tmpPath);
233 GetSystemLibraryPaths(Paths);
237 Path::GetLLVMDefaultConfigDir() {
238 return Path("/etc/llvm/");
242 Path::GetUserHomeDirectory() {
243 const char* home = getenv("HOME");
246 if (result.set(home))
249 return GetRootDirectory();
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 /// 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(__CYGWIN__)
268 snprintf(exe_link, sizeof(exe_link), "/proc/%d/exe", getpid());
269 char exe_path[MAXPATHLEN];
270 ssize_t len = readlink(exe_link, exe_path, sizeof(exe_path));
271 if (len > 0 && len < MAXPATHLEN - 1) {
272 exe_path[len] = '\0';
273 return Path(std::string(exe_path));
275 #elif defined(HAVE_DLFCN_H)
276 // Use dladdr to get executable path if available.
278 int err = dladdr(MainAddr, &DLInfo);
280 return Path(std::string(DLInfo.dli_fname));
286 std::string Path::getDirname() const {
287 return getDirnameCharSep(path, '/');
291 Path::getBasename() const {
292 // Find the last slash
293 std::string::size_type slash = path.rfind('/');
294 if (slash == std::string::npos)
299 std::string::size_type dot = path.rfind('.');
300 if (dot == std::string::npos || dot < slash)
301 return path.substr(slash);
303 return path.substr(slash, dot - slash);
306 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
307 assert(len < 1024 && "Request for magic string too long");
308 char* buf = (char*) alloca(1 + len);
309 int fd = ::open(path.c_str(), O_RDONLY);
312 ssize_t bytes_read = ::read(fd, buf, len);
314 if (ssize_t(len) != bytes_read) {
318 Magic.assign(buf,len);
323 Path::exists() const {
324 return 0 == access(path.c_str(), F_OK );
328 Path::isDirectory() const {
330 if (0 != stat(path.c_str(), &buf))
332 return buf.st_mode & S_IFDIR ? true : false;
336 Path::canRead() const {
337 return 0 == access(path.c_str(), F_OK | R_OK );
341 Path::canWrite() const {
342 return 0 == access(path.c_str(), F_OK | W_OK );
346 Path::canExecute() const {
347 if (0 != access(path.c_str(), R_OK | X_OK ))
350 if (0 != stat(path.c_str(), &buf))
352 if (!S_ISREG(buf.st_mode))
358 Path::getLast() const {
359 // Find the last slash
360 size_t pos = path.rfind('/');
362 // Handle the corner cases
363 if (pos == std::string::npos)
366 // If the last character is a slash
367 if (pos == path.length()-1) {
368 // Find the second to last slash
369 size_t pos2 = path.rfind('/', pos-1);
370 if (pos2 == std::string::npos)
371 return path.substr(0,pos);
373 return path.substr(pos2+1,pos-pos2-1);
375 // Return everything after the last slash
376 return path.substr(pos+1);
380 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
381 if (!fsIsValid || update) {
383 if (0 != stat(path.c_str(), &buf)) {
384 MakeErrMsg(ErrStr, path + ": can't get status of file");
387 status.fileSize = buf.st_size;
388 status.modTime.fromEpochTime(buf.st_mtime);
389 status.mode = buf.st_mode;
390 status.user = buf.st_uid;
391 status.group = buf.st_gid;
392 status.uniqueID = uint64_t(buf.st_ino);
393 status.isDir = S_ISDIR(buf.st_mode);
394 status.isFile = S_ISREG(buf.st_mode);
400 static bool AddPermissionBits(const Path &File, int bits) {
401 // Get the umask value from the operating system. We want to use it
402 // when changing the file's permissions. Since calling umask() sets
403 // the umask and returns its old value, we must call it a second
404 // time to reset it to the user's preference.
405 int mask = umask(0777); // The arg. to umask is arbitrary.
406 umask(mask); // Restore the umask.
408 // Get the file's current mode.
410 if (0 != stat(File.toString().c_str(), &buf))
412 // Change the file to have whichever permissions bits from 'bits'
413 // that the umask would not disable.
414 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
419 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
420 if (!AddPermissionBits(*this, 0444))
421 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
425 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
426 if (!AddPermissionBits(*this, 0222))
427 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
431 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
432 if (!AddPermissionBits(*this, 0111))
433 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
438 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
439 DIR* direntries = ::opendir(path.c_str());
441 return MakeErrMsg(ErrMsg, path + ": can't open directory");
443 std::string dirPath = path;
444 if (!lastIsSlash(dirPath))
448 struct dirent* de = ::readdir(direntries);
449 for ( ; de != 0; de = ::readdir(direntries)) {
450 if (de->d_name[0] != '.') {
451 Path aPath(dirPath + (const char*)de->d_name);
453 if (0 != lstat(aPath.path.c_str(), &st)) {
454 if (S_ISLNK(st.st_mode))
455 continue; // dangling symlink -- ignore
456 return MakeErrMsg(ErrMsg,
457 aPath.path + ": can't determine file object type");
459 result.insert(aPath);
463 closedir(direntries);
468 Path::set(const std::string& a_path) {
471 std::string save(path);
481 Path::appendComponent(const std::string& name) {
484 std::string save(path);
485 if (!lastIsSlash(path))
496 Path::eraseComponent() {
497 size_t slashpos = path.rfind('/',path.size());
498 if (slashpos == 0 || slashpos == std::string::npos) {
502 if (slashpos == path.size() - 1)
503 slashpos = path.rfind('/',slashpos-1);
504 if (slashpos == std::string::npos) {
508 path.erase(slashpos);
513 Path::appendSuffix(const std::string& suffix) {
514 std::string save(path);
525 Path::eraseSuffix() {
526 std::string save = path;
527 size_t dotpos = path.rfind('.',path.size());
528 size_t slashpos = path.rfind('/',path.size());
529 if (dotpos != std::string::npos) {
530 if (slashpos == std::string::npos || dotpos > slashpos+1) {
531 path.erase(dotpos, path.size()-dotpos);
540 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
542 if (access(beg, F_OK | R_OK | W_OK) == 0)
545 if (create_parents) {
549 for (; c != beg; --c)
552 // Recurse to handling the parent directory.
554 bool x = createDirectoryHelper(beg, c, create_parents);
557 // Return if we encountered an error.
565 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
569 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
570 // Get a writeable copy of the path name
571 char pathname[MAXPATHLEN];
572 path.copy(pathname,MAXPATHLEN);
574 // Null-terminate the last component
575 size_t lastchar = path.length() - 1 ;
577 if (pathname[lastchar] != '/')
580 pathname[lastchar] = 0;
582 if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
583 return MakeErrMsg(ErrMsg,
584 std::string(pathname) + ": can't create directory");
590 Path::createFileOnDisk(std::string* ErrMsg) {
592 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
594 return MakeErrMsg(ErrMsg, path + ": can't create file");
600 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
601 // Make this into a unique file name
602 if (makeUnique( reuse_current, ErrMsg ))
606 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
608 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
614 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
615 // Get the status so we can determin if its a file or directory
617 if (0 != stat(path.c_str(), &buf)) {
618 MakeErrMsg(ErrStr, path + ": can't get status of file");
622 // Note: this check catches strange situations. In all cases, LLVM should
623 // only be involved in the creation and deletion of regular files. This
624 // check ensures that what we're trying to erase is a regular file. It
625 // effectively prevents LLVM from erasing things like /dev/null, any block
626 // special file, or other things that aren't "regular" files.
627 if (S_ISREG(buf.st_mode)) {
628 if (unlink(path.c_str()) != 0)
629 return MakeErrMsg(ErrStr, path + ": can't destroy file");
633 if (!S_ISDIR(buf.st_mode)) {
634 if (ErrStr) *ErrStr = "not a file or directory";
638 if (remove_contents) {
639 // Recursively descend the directory to remove its contents.
640 std::string cmd = "/bin/rm -rf " + path;
645 // Otherwise, try to just remove the one directory.
646 char pathname[MAXPATHLEN];
647 path.copy(pathname, MAXPATHLEN);
648 size_t lastchar = path.length() - 1;
649 if (pathname[lastchar] == '/')
650 pathname[lastchar] = 0;
652 pathname[lastchar+1] = 0;
654 if (rmdir(pathname) != 0)
655 return MakeErrMsg(ErrStr,
656 std::string(pathname) + ": can't erase directory");
661 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
662 if (0 != ::rename(path.c_str(), newName.c_str()))
663 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
664 newName.toString() + "' ");
669 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
671 utb.actime = si.modTime.toPosixTime();
672 utb.modtime = utb.actime;
673 if (0 != ::utime(path.c_str(),&utb))
674 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
675 if (0 != ::chmod(path.c_str(),si.mode))
676 return MakeErrMsg(ErrStr, path + ": can't set mode");
681 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
684 inFile = ::open(Src.c_str(), O_RDONLY);
686 return MakeErrMsg(ErrMsg, Src.toString() +
687 ": can't open source file to copy");
689 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
692 return MakeErrMsg(ErrMsg, Dest.toString() +
693 ": can't create destination file for copy");
696 char Buffer[16*1024];
697 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
699 if (errno != EINTR && errno != EAGAIN) {
702 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file: ");
705 char *BufPtr = Buffer;
707 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
708 if (AmtWritten == -1) {
709 if (errno != EINTR && errno != EAGAIN) {
712 return MakeErrMsg(ErrMsg, Dest.toString() +
713 ": can't write destination file: ");
717 BufPtr += AmtWritten;
728 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
729 if (reuse_current && !exists())
730 return false; // File doesn't exist already, just use it!
732 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
733 // mktemp or our own implementation.
734 char *FNBuffer = (char*) alloca(path.size()+8);
735 path.copy(FNBuffer,path.size());
736 strcpy(FNBuffer+path.size(), "-XXXXXX");
738 #if defined(HAVE_MKSTEMP)
740 if ((TempFD = mkstemp(FNBuffer)) == -1)
741 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
743 // We don't need to hold the temp file descriptor... we will trust that no one
744 // will overwrite/delete the file before we can open it again.
749 #elif defined(HAVE_MKTEMP)
750 // If we don't have mkstemp, use the old and obsolete mktemp function.
751 if (mktemp(FNBuffer) == 0)
752 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
757 // Okay, looks like we have to do it all by our lonesome.
758 static unsigned FCounter = 0;
759 unsigned offset = path.size() + 1;
760 while ( FCounter < 999999 && exists()) {
761 sprintf(FNBuffer+offset,"%06u",++FCounter);
764 if (FCounter > 999999)
765 return MakeErrMsg(ErrMsg,
766 path + ": can't make unique filename: too many files");
771 const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
772 int Flags = MAP_PRIVATE;
776 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
777 if (BasePtr == MAP_FAILED)
779 return (const char*)BasePtr;
782 void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
783 ::munmap((void*)BasePtr, FileSize);
786 } // end llvm namespace