Remove Path::isAbsolute.
[oota-llvm.git] / lib / Support / Unix / Path.inc
1 //===- llvm/Support/Unix/Path.cpp - Unix Path Implementation -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Unix specific portion of the Path class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic UNIX code that
16 //===          is guaranteed to work on *all* UNIX variants.
17 //===----------------------------------------------------------------------===//
18
19 #include "Unix.h"
20 #if HAVE_SYS_STAT_H
21 #include <sys/stat.h>
22 #endif
23 #if HAVE_FCNTL_H
24 #include <fcntl.h>
25 #endif
26 #ifdef HAVE_SYS_MMAN_H
27 #include <sys/mman.h>
28 #endif
29 #ifdef HAVE_SYS_STAT_H
30 #include <sys/stat.h>
31 #endif
32 #if HAVE_UTIME_H
33 #include <utime.h>
34 #endif
35 #if HAVE_TIME_H
36 #include <time.h>
37 #endif
38 #if HAVE_DIRENT_H
39 # include <dirent.h>
40 # define NAMLEN(dirent) strlen((dirent)->d_name)
41 #else
42 # define dirent direct
43 # define NAMLEN(dirent) (dirent)->d_namlen
44 # if HAVE_SYS_NDIR_H
45 #  include <sys/ndir.h>
46 # endif
47 # if HAVE_SYS_DIR_H
48 #  include <sys/dir.h>
49 # endif
50 # if HAVE_NDIR_H
51 #  include <ndir.h>
52 # endif
53 #endif
54
55 #if HAVE_DLFCN_H
56 #include <dlfcn.h>
57 #endif
58
59 #ifdef __APPLE__
60 #include <mach-o/dyld.h>
61 #endif
62
63 // For GNU Hurd
64 #if defined(__GNU__) && !defined(MAXPATHLEN)
65 # define MAXPATHLEN 4096
66 #endif
67
68 // Put in a hack for Cygwin which falsely reports that the mkdtemp function
69 // is available when it is not.
70 #ifdef __CYGWIN__
71 # undef HAVE_MKDTEMP
72 #endif
73
74 namespace {
75 inline bool lastIsSlash(const std::string& path) {
76   return !path.empty() && path[path.length() - 1] == '/';
77 }
78
79 }
80
81 namespace llvm {
82 using namespace sys;
83
84 const char sys::PathSeparator = ':';
85
86 StringRef Path::GetEXESuffix() {
87   return StringRef();
88 }
89
90 Path::Path(StringRef p)
91   : path(p) {}
92
93 Path::Path(const char *StrStart, unsigned StrLen)
94   : path(StrStart, StrLen) {}
95
96 Path&
97 Path::operator=(StringRef that) {
98   path.assign(that.data(), that.size());
99   return *this;
100 }
101
102 bool
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
108   // ENAMETOLONG.
109   return !path.empty();
110 }
111
112 Path
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)) {
119     MakeErrMsg(ErrMsg,
120                std::string(pathname) + ": can't create temporary directory");
121     return Path();
122   }
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";
131   int fd = 0;
132   if (-1 == (fd = mkstemp(pathname))) {
133     MakeErrMsg(ErrMsg,
134       std::string(pathname) + ": can't create temporary directory");
135     return Path();
136   }
137   ::close(fd);
138   ::unlink(pathname); // start race condition, ignore errors
139   if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
140     MakeErrMsg(ErrMsg,
141       std::string(pathname) + ": can't create temporary directory");
142     return Path();
143   }
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);
153   if (TmpName == 0) {
154     MakeErrMsg(ErrMsg,
155       std::string(TmpName) + ": can't create unique directory name");
156     return Path();
157   }
158   if (-1 == ::mkdir(TmpName, S_IRWXU)) {
159     MakeErrMsg(ErrMsg,
160         std::string(TmpName) + ": can't create temporary directory");
161     return Path();
162   }
163   return Path(TmpName);
164 #else
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];
175   do {
176     num++;
177     sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
178   } while ( 0 == access(pathname, F_OK ) );
179   if (-1 == ::mkdir(pathname, S_IRWXU)) {
180     MakeErrMsg(ErrMsg,
181       std::string(pathname) + ": can't create temporary directory");
182     return Path();
183   }
184   return Path(pathname);
185 #endif
186 }
187
188 Path
189 Path::GetCurrentDirectory() {
190   char pathname[MAXPATHLEN];
191   if (!getcwd(pathname, MAXPATHLEN)) {
192     assert(false && "Could not query current working directory.");
193     return Path();
194   }
195
196   return Path(pathname);
197 }
198
199 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
200     defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
201     defined(__linux__) || defined(__CYGWIN__)
202 static int
203 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
204     const char *dir, const char *bin)
205 {
206   struct stat sb;
207
208   snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
209   if (realpath(buf, ret) == NULL)
210     return (1);
211   if (stat(buf, &sb) != 0)
212     return (1);
213
214   return (0);
215 }
216
217 static char *
218 getprogpath(char ret[PATH_MAX], const char *bin)
219 {
220   char *pv, *s, *t, buf[PATH_MAX];
221
222   /* First approach: absolute path. */
223   if (bin[0] == '/') {
224     if (test_dir(buf, ret, "/", bin) == 0)
225       return (ret);
226     return (NULL);
227   }
228
229   /* Second approach: relative path. */
230   if (strchr(bin, '/') != NULL) {
231     if (getcwd(buf, PATH_MAX) == NULL)
232       return (NULL);
233     if (test_dir(buf, ret, buf, bin) == 0)
234       return (ret);
235     return (NULL);
236   }
237
238   /* Third approach: $PATH */
239   if ((pv = getenv("PATH")) == NULL)
240     return (NULL);
241   s = pv = strdup(pv);
242   if (pv == NULL)
243     return (NULL);
244   while ((t = strsep(&s, ":")) != NULL) {
245     if (test_dir(buf, ret, t, bin) == 0) {
246       free(pv);
247       return (ret);
248     }
249   }
250   free(pv);
251   return (NULL);
252 }
253 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
254
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);
268   }
269 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
270       defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__)
271   char exe_path[PATH_MAX];
272
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));
281       if (len >= 0)
282           return Path(StringRef(exe_path, len));
283   } else {
284       // Fall back to the classical detection.
285       if (getprogpath(exe_path, argv0) != NULL)
286           return Path(exe_path);
287   }
288 #elif defined(HAVE_DLFCN_H)
289   // Use dladdr to get executable path if available.
290   Dl_info DLInfo;
291   int err = dladdr(MainAddr, &DLInfo);
292   if (err == 0)
293     return Path();
294
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);
300 #else
301 #error GetMainExecutable is not implemented on this host yet.
302 #endif
303   return Path();
304 }
305
306 bool Path::getMagicNumber(std::string &Magic, unsigned len) const {
307   assert(len < 1024 && "Request for magic string too long");
308   char Buf[1025];
309   int fd = ::open(path.c_str(), O_RDONLY);
310   if (fd < 0)
311     return false;
312   ssize_t bytes_read = ::read(fd, Buf, len);
313   ::close(fd);
314   if (ssize_t(len) != bytes_read)
315     return false;
316   Magic.assign(Buf, len);
317   return true;
318 }
319
320 bool
321 Path::exists() const {
322   return 0 == access(path.c_str(), F_OK );
323 }
324
325 bool
326 Path::isDirectory() const {
327   struct stat buf;
328   if (0 != stat(path.c_str(), &buf))
329     return false;
330   return ((buf.st_mode & S_IFMT) == S_IFDIR) ? true : false;
331 }
332
333 bool
334 Path::isSymLink() const {
335   struct stat buf;
336   if (0 != lstat(path.c_str(), &buf))
337     return false;
338   return S_ISLNK(buf.st_mode);
339 }
340
341
342 bool
343 Path::canRead() const {
344   return 0 == access(path.c_str(), R_OK);
345 }
346
347 bool
348 Path::canWrite() const {
349   return 0 == access(path.c_str(), W_OK);
350 }
351
352 bool
353 Path::isRegularFile() const {
354   // Get the status so we can determine if it's a file or directory
355   struct stat buf;
356
357   if (0 != stat(path.c_str(), &buf))
358     return false;
359
360   if (S_ISREG(buf.st_mode))
361     return true;
362
363   return false;
364 }
365
366 bool
367 Path::canExecute() const {
368   if (0 != access(path.c_str(), R_OK | X_OK ))
369     return false;
370   struct stat buf;
371   if (0 != stat(path.c_str(), &buf))
372     return false;
373   if (!S_ISREG(buf.st_mode))
374     return false;
375   return true;
376 }
377
378 const FileStatus *
379 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
380   if (!fsIsValid || update) {
381     struct stat buf;
382     if (0 != stat(path.c_str(), &buf)) {
383       MakeErrMsg(ErrStr, path + ": can't get status of file");
384       return 0;
385     }
386     status.fileSize = buf.st_size;
387     status.modTime.fromEpochTime(buf.st_mtime);
388     status.mode = buf.st_mode;
389     status.user = buf.st_uid;
390     status.group = buf.st_gid;
391     status.uniqueID = uint64_t(buf.st_ino);
392     status.isDir  = S_ISDIR(buf.st_mode);
393     status.isFile = S_ISREG(buf.st_mode);
394     fsIsValid = true;
395   }
396   return &status;
397 }
398
399 static bool AddPermissionBits(const Path &File, int bits) {
400   // Get the umask value from the operating system.  We want to use it
401   // when changing the file's permissions. Since calling umask() sets
402   // the umask and returns its old value, we must call it a second
403   // time to reset it to the user's preference.
404   int mask = umask(0777); // The arg. to umask is arbitrary.
405   umask(mask);            // Restore the umask.
406
407   // Get the file's current mode.
408   struct stat buf;
409   if (0 != stat(File.c_str(), &buf))
410     return false;
411   // Change the file to have whichever permissions bits from 'bits'
412   // that the umask would not disable.
413   if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
414       return false;
415   return true;
416 }
417
418 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
419   if (!AddPermissionBits(*this, 0444))
420     return MakeErrMsg(ErrMsg, path + ": can't make file readable");
421   return false;
422 }
423
424 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
425   if (!AddPermissionBits(*this, 0222))
426     return MakeErrMsg(ErrMsg, path + ": can't make file writable");
427   return false;
428 }
429
430 bool
431 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
432   DIR* direntries = ::opendir(path.c_str());
433   if (direntries == 0)
434     return MakeErrMsg(ErrMsg, path + ": can't open directory");
435
436   std::string dirPath = path;
437   if (!lastIsSlash(dirPath))
438     dirPath += '/';
439
440   result.clear();
441   struct dirent* de = ::readdir(direntries);
442   for ( ; de != 0; de = ::readdir(direntries)) {
443     if (de->d_name[0] != '.') {
444       Path aPath(dirPath + (const char*)de->d_name);
445       struct stat st;
446       if (0 != lstat(aPath.path.c_str(), &st)) {
447         if (S_ISLNK(st.st_mode))
448           continue; // dangling symlink -- ignore
449         return MakeErrMsg(ErrMsg,
450                           aPath.path +  ": can't determine file object type");
451       }
452       result.insert(aPath);
453     }
454   }
455
456   closedir(direntries);
457   return false;
458 }
459
460 bool
461 Path::set(StringRef a_path) {
462   if (a_path.empty())
463     return false;
464   path = a_path;
465   return true;
466 }
467
468 bool
469 Path::appendComponent(StringRef name) {
470   if (name.empty())
471     return false;
472   if (!lastIsSlash(path))
473     path += '/';
474   path += name;
475   return true;
476 }
477
478 bool
479 Path::eraseComponent() {
480   size_t slashpos = path.rfind('/',path.size());
481   if (slashpos == 0 || slashpos == std::string::npos) {
482     path.erase();
483     return true;
484   }
485   if (slashpos == path.size() - 1)
486     slashpos = path.rfind('/',slashpos-1);
487   if (slashpos == std::string::npos) {
488     path.erase();
489     return true;
490   }
491   path.erase(slashpos);
492   return true;
493 }
494
495 bool
496 Path::eraseSuffix() {
497   size_t dotpos = path.rfind('.',path.size());
498   size_t slashpos = path.rfind('/',path.size());
499   if (dotpos != std::string::npos) {
500     if (slashpos == std::string::npos || dotpos > slashpos+1) {
501       path.erase(dotpos, path.size()-dotpos);
502       return true;
503     }
504   }
505   return false;
506 }
507
508 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
509
510   if (access(beg, R_OK | W_OK) == 0)
511     return false;
512
513   if (create_parents) {
514
515     char* c = end;
516
517     for (; c != beg; --c)
518       if (*c == '/') {
519
520         // Recurse to handling the parent directory.
521         *c = '\0';
522         bool x = createDirectoryHelper(beg, c, create_parents);
523         *c = '/';
524
525         // Return if we encountered an error.
526         if (x)
527           return true;
528
529         break;
530       }
531   }
532
533   return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
534 }
535
536 bool
537 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
538   // Get a writeable copy of the path name
539   std::string pathname(path);
540
541   // Null-terminate the last component
542   size_t lastchar = path.length() - 1 ;
543
544   if (pathname[lastchar] != '/')
545     ++lastchar;
546
547   pathname[lastchar] = '\0';
548
549   if (createDirectoryHelper(&pathname[0], &pathname[lastchar], create_parents))
550     return MakeErrMsg(ErrMsg, pathname + ": can't create directory");
551
552   return false;
553 }
554
555 bool
556 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
557   // Make this into a unique file name
558   if (makeUnique( reuse_current, ErrMsg ))
559     return true;
560
561   // create the file
562   int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
563   if (fd < 0)
564     return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
565   ::close(fd);
566   return false;
567 }
568
569 bool
570 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
571   // Get the status so we can determine if it's a file or directory.
572   struct stat buf;
573   if (0 != stat(path.c_str(), &buf)) {
574     MakeErrMsg(ErrStr, path + ": can't get status of file");
575     return true;
576   }
577
578   // Note: this check catches strange situations. In all cases, LLVM should
579   // only be involved in the creation and deletion of regular files.  This
580   // check ensures that what we're trying to erase is a regular file. It
581   // effectively prevents LLVM from erasing things like /dev/null, any block
582   // special file, or other things that aren't "regular" files.
583   if (S_ISREG(buf.st_mode)) {
584     if (unlink(path.c_str()) != 0)
585       return MakeErrMsg(ErrStr, path + ": can't destroy file");
586     return false;
587   }
588
589   if (!S_ISDIR(buf.st_mode)) {
590     if (ErrStr) *ErrStr = "not a file or directory";
591     return true;
592   }
593
594   if (remove_contents) {
595     // Recursively descend the directory to remove its contents.
596     std::string cmd = "/bin/rm -rf " + path;
597     if (system(cmd.c_str()) != 0) {
598       MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
599       return true;
600     }
601     return false;
602   }
603
604   // Otherwise, try to just remove the one directory.
605   std::string pathname(path);
606   size_t lastchar = path.length() - 1;
607   if (pathname[lastchar] == '/')
608     pathname[lastchar] = '\0';
609   else
610     pathname[lastchar+1] = '\0';
611
612   if (rmdir(pathname.c_str()) != 0)
613     return MakeErrMsg(ErrStr, pathname + ": can't erase directory");
614   return false;
615 }
616
617 bool
618 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
619   if (0 != ::rename(path.c_str(), newName.c_str()))
620     return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
621                newName.str() + "'");
622   return false;
623 }
624
625 bool
626 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
627   struct utimbuf utb;
628   utb.actime = si.modTime.toPosixTime();
629   utb.modtime = utb.actime;
630   if (0 != ::utime(path.c_str(),&utb))
631     return MakeErrMsg(ErrStr, path + ": can't set file modification time");
632   if (0 != ::chmod(path.c_str(),si.mode))
633     return MakeErrMsg(ErrStr, path + ": can't set mode");
634   return false;
635 }
636
637 bool
638 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
639   bool Exists;
640   if (reuse_current && (fs::exists(path, Exists) || !Exists))
641     return false; // File doesn't exist already, just use it!
642
643   // Append an XXXXXX pattern to the end of the file for use with mkstemp,
644   // mktemp or our own implementation.
645   // This uses std::vector instead of SmallVector to avoid a dependence on
646   // libSupport. And performance isn't critical here.
647   std::vector<char> Buf;
648   Buf.resize(path.size()+8);
649   char *FNBuffer = &Buf[0];
650     path.copy(FNBuffer,path.size());
651   bool isdir;
652   if (!fs::is_directory(path, isdir) && isdir)
653     strcpy(FNBuffer+path.size(), "/XXXXXX");
654   else
655     strcpy(FNBuffer+path.size(), "-XXXXXX");
656
657 #if defined(HAVE_MKSTEMP)
658   int TempFD;
659   if ((TempFD = mkstemp(FNBuffer)) == -1)
660     return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
661
662   // We don't need to hold the temp file descriptor... we will trust that no one
663   // will overwrite/delete the file before we can open it again.
664   close(TempFD);
665
666   // Save the name
667   path = FNBuffer;
668
669   // By default mkstemp sets the mode to 0600, so update mode bits now.
670   AddPermissionBits (*this, 0666);
671 #elif defined(HAVE_MKTEMP)
672   // If we don't have mkstemp, use the old and obsolete mktemp function.
673   if (mktemp(FNBuffer) == 0)
674     return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
675
676   // Save the name
677   path = FNBuffer;
678 #else
679   // Okay, looks like we have to do it all by our lonesome.
680   static unsigned FCounter = 0;
681   // Try to initialize with unique value.
682   if (FCounter == 0) FCounter = ((unsigned)getpid() & 0xFFFF) << 8;
683   char* pos = strstr(FNBuffer, "XXXXXX");
684   do {
685     if (++FCounter > 0xFFFFFF) {
686       return MakeErrMsg(ErrMsg,
687         path + ": can't make unique filename: too many files");
688     }
689     sprintf(pos, "%06X", FCounter);
690     path = FNBuffer;
691   } while (exists());
692   // POSSIBLE SECURITY BUG: An attacker can easily guess the name and exploit
693   // LLVM.
694 #endif
695   return false;
696 }
697 } // end llvm namespace