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 bool
113 Path::isAbsolute(const char *NameStart, unsigned NameLen) {
114   assert(NameStart);
115   if (NameLen == 0)
116     return false;
117   return NameStart[0] == '/';
118 }
119
120 Path
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)) {
127     MakeErrMsg(ErrMsg,
128                std::string(pathname) + ": can't create temporary directory");
129     return Path();
130   }
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";
139   int fd = 0;
140   if (-1 == (fd = mkstemp(pathname))) {
141     MakeErrMsg(ErrMsg,
142       std::string(pathname) + ": can't create temporary directory");
143     return Path();
144   }
145   ::close(fd);
146   ::unlink(pathname); // start race condition, ignore errors
147   if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
148     MakeErrMsg(ErrMsg,
149       std::string(pathname) + ": can't create temporary directory");
150     return Path();
151   }
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);
161   if (TmpName == 0) {
162     MakeErrMsg(ErrMsg,
163       std::string(TmpName) + ": can't create unique directory name");
164     return Path();
165   }
166   if (-1 == ::mkdir(TmpName, S_IRWXU)) {
167     MakeErrMsg(ErrMsg,
168         std::string(TmpName) + ": can't create temporary directory");
169     return Path();
170   }
171   return Path(TmpName);
172 #else
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];
183   do {
184     num++;
185     sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
186   } while ( 0 == access(pathname, F_OK ) );
187   if (-1 == ::mkdir(pathname, S_IRWXU)) {
188     MakeErrMsg(ErrMsg,
189       std::string(pathname) + ": can't create temporary directory");
190     return Path();
191   }
192   return Path(pathname);
193 #endif
194 }
195
196 Path
197 Path::GetCurrentDirectory() {
198   char pathname[MAXPATHLEN];
199   if (!getcwd(pathname, MAXPATHLEN)) {
200     assert(false && "Could not query current working directory.");
201     return Path();
202   }
203
204   return Path(pathname);
205 }
206
207 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
208     defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
209     defined(__linux__) || defined(__CYGWIN__)
210 static int
211 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
212     const char *dir, const char *bin)
213 {
214   struct stat sb;
215
216   snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
217   if (realpath(buf, ret) == NULL)
218     return (1);
219   if (stat(buf, &sb) != 0)
220     return (1);
221
222   return (0);
223 }
224
225 static char *
226 getprogpath(char ret[PATH_MAX], const char *bin)
227 {
228   char *pv, *s, *t, buf[PATH_MAX];
229
230   /* First approach: absolute path. */
231   if (bin[0] == '/') {
232     if (test_dir(buf, ret, "/", bin) == 0)
233       return (ret);
234     return (NULL);
235   }
236
237   /* Second approach: relative path. */
238   if (strchr(bin, '/') != NULL) {
239     if (getcwd(buf, PATH_MAX) == NULL)
240       return (NULL);
241     if (test_dir(buf, ret, buf, bin) == 0)
242       return (ret);
243     return (NULL);
244   }
245
246   /* Third approach: $PATH */
247   if ((pv = getenv("PATH")) == NULL)
248     return (NULL);
249   s = pv = strdup(pv);
250   if (pv == NULL)
251     return (NULL);
252   while ((t = strsep(&s, ":")) != NULL) {
253     if (test_dir(buf, ret, t, bin) == 0) {
254       free(pv);
255       return (ret);
256     }
257   }
258   free(pv);
259   return (NULL);
260 }
261 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
262
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);
276   }
277 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
278       defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__)
279   char exe_path[PATH_MAX];
280
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));
289       if (len >= 0)
290           return Path(StringRef(exe_path, len));
291   } else {
292       // Fall back to the classical detection.
293       if (getprogpath(exe_path, argv0) != NULL)
294           return Path(exe_path);
295   }
296 #elif defined(HAVE_DLFCN_H)
297   // Use dladdr to get executable path if available.
298   Dl_info DLInfo;
299   int err = dladdr(MainAddr, &DLInfo);
300   if (err == 0)
301     return Path();
302
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);
308 #else
309 #error GetMainExecutable is not implemented on this host yet.
310 #endif
311   return Path();
312 }
313
314 bool Path::getMagicNumber(std::string &Magic, unsigned len) const {
315   assert(len < 1024 && "Request for magic string too long");
316   char Buf[1025];
317   int fd = ::open(path.c_str(), O_RDONLY);
318   if (fd < 0)
319     return false;
320   ssize_t bytes_read = ::read(fd, Buf, len);
321   ::close(fd);
322   if (ssize_t(len) != bytes_read)
323     return false;
324   Magic.assign(Buf, len);
325   return true;
326 }
327
328 bool
329 Path::exists() const {
330   return 0 == access(path.c_str(), F_OK );
331 }
332
333 bool
334 Path::isDirectory() const {
335   struct stat buf;
336   if (0 != stat(path.c_str(), &buf))
337     return false;
338   return ((buf.st_mode & S_IFMT) == S_IFDIR) ? true : false;
339 }
340
341 bool
342 Path::isSymLink() const {
343   struct stat buf;
344   if (0 != lstat(path.c_str(), &buf))
345     return false;
346   return S_ISLNK(buf.st_mode);
347 }
348
349
350 bool
351 Path::canRead() const {
352   return 0 == access(path.c_str(), R_OK);
353 }
354
355 bool
356 Path::canWrite() const {
357   return 0 == access(path.c_str(), W_OK);
358 }
359
360 bool
361 Path::isRegularFile() const {
362   // Get the status so we can determine if it's a file or directory
363   struct stat buf;
364
365   if (0 != stat(path.c_str(), &buf))
366     return false;
367
368   if (S_ISREG(buf.st_mode))
369     return true;
370
371   return false;
372 }
373
374 bool
375 Path::canExecute() const {
376   if (0 != access(path.c_str(), R_OK | X_OK ))
377     return false;
378   struct stat buf;
379   if (0 != stat(path.c_str(), &buf))
380     return false;
381   if (!S_ISREG(buf.st_mode))
382     return false;
383   return true;
384 }
385
386 const FileStatus *
387 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
388   if (!fsIsValid || update) {
389     struct stat buf;
390     if (0 != stat(path.c_str(), &buf)) {
391       MakeErrMsg(ErrStr, path + ": can't get status of file");
392       return 0;
393     }
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);
402     fsIsValid = true;
403   }
404   return &status;
405 }
406
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.
414
415   // Get the file's current mode.
416   struct stat buf;
417   if (0 != stat(File.c_str(), &buf))
418     return false;
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)
422       return false;
423   return true;
424 }
425
426 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
427   if (!AddPermissionBits(*this, 0444))
428     return MakeErrMsg(ErrMsg, path + ": can't make file readable");
429   return false;
430 }
431
432 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
433   if (!AddPermissionBits(*this, 0222))
434     return MakeErrMsg(ErrMsg, path + ": can't make file writable");
435   return false;
436 }
437
438 bool
439 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
440   DIR* direntries = ::opendir(path.c_str());
441   if (direntries == 0)
442     return MakeErrMsg(ErrMsg, path + ": can't open directory");
443
444   std::string dirPath = path;
445   if (!lastIsSlash(dirPath))
446     dirPath += '/';
447
448   result.clear();
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);
453       struct stat st;
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");
459       }
460       result.insert(aPath);
461     }
462   }
463
464   closedir(direntries);
465   return false;
466 }
467
468 bool
469 Path::set(StringRef a_path) {
470   if (a_path.empty())
471     return false;
472   path = a_path;
473   return true;
474 }
475
476 bool
477 Path::appendComponent(StringRef name) {
478   if (name.empty())
479     return false;
480   if (!lastIsSlash(path))
481     path += '/';
482   path += name;
483   return true;
484 }
485
486 bool
487 Path::eraseComponent() {
488   size_t slashpos = path.rfind('/',path.size());
489   if (slashpos == 0 || slashpos == std::string::npos) {
490     path.erase();
491     return true;
492   }
493   if (slashpos == path.size() - 1)
494     slashpos = path.rfind('/',slashpos-1);
495   if (slashpos == std::string::npos) {
496     path.erase();
497     return true;
498   }
499   path.erase(slashpos);
500   return true;
501 }
502
503 bool
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);
510       return true;
511     }
512   }
513   return false;
514 }
515
516 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
517
518   if (access(beg, R_OK | W_OK) == 0)
519     return false;
520
521   if (create_parents) {
522
523     char* c = end;
524
525     for (; c != beg; --c)
526       if (*c == '/') {
527
528         // Recurse to handling the parent directory.
529         *c = '\0';
530         bool x = createDirectoryHelper(beg, c, create_parents);
531         *c = '/';
532
533         // Return if we encountered an error.
534         if (x)
535           return true;
536
537         break;
538       }
539   }
540
541   return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
542 }
543
544 bool
545 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
546   // Get a writeable copy of the path name
547   std::string pathname(path);
548
549   // Null-terminate the last component
550   size_t lastchar = path.length() - 1 ;
551
552   if (pathname[lastchar] != '/')
553     ++lastchar;
554
555   pathname[lastchar] = '\0';
556
557   if (createDirectoryHelper(&pathname[0], &pathname[lastchar], create_parents))
558     return MakeErrMsg(ErrMsg, pathname + ": can't create directory");
559
560   return false;
561 }
562
563 bool
564 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
565   // Make this into a unique file name
566   if (makeUnique( reuse_current, ErrMsg ))
567     return true;
568
569   // create the file
570   int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
571   if (fd < 0)
572     return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
573   ::close(fd);
574   return false;
575 }
576
577 bool
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.
580   struct stat buf;
581   if (0 != stat(path.c_str(), &buf)) {
582     MakeErrMsg(ErrStr, path + ": can't get status of file");
583     return true;
584   }
585
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");
594     return false;
595   }
596
597   if (!S_ISDIR(buf.st_mode)) {
598     if (ErrStr) *ErrStr = "not a file or directory";
599     return true;
600   }
601
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.");
607       return true;
608     }
609     return false;
610   }
611
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';
617   else
618     pathname[lastchar+1] = '\0';
619
620   if (rmdir(pathname.c_str()) != 0)
621     return MakeErrMsg(ErrStr, pathname + ": can't erase directory");
622   return false;
623 }
624
625 bool
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() + "'");
630   return false;
631 }
632
633 bool
634 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
635   struct utimbuf utb;
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");
642   return false;
643 }
644
645 bool
646 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
647   bool Exists;
648   if (reuse_current && (fs::exists(path, Exists) || !Exists))
649     return false; // File doesn't exist already, just use it!
650
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());
659   bool isdir;
660   if (!fs::is_directory(path, isdir) && isdir)
661     strcpy(FNBuffer+path.size(), "/XXXXXX");
662   else
663     strcpy(FNBuffer+path.size(), "-XXXXXX");
664
665 #if defined(HAVE_MKSTEMP)
666   int TempFD;
667   if ((TempFD = mkstemp(FNBuffer)) == -1)
668     return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
669
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.
672   close(TempFD);
673
674   // Save the name
675   path = FNBuffer;
676
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");
683
684   // Save the name
685   path = FNBuffer;
686 #else
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");
692   do {
693     if (++FCounter > 0xFFFFFF) {
694       return MakeErrMsg(ErrMsg,
695         path + ": can't make unique filename: too many files");
696     }
697     sprintf(pos, "%06X", FCounter);
698     path = FNBuffer;
699   } while (exists());
700   // POSSIBLE SECURITY BUG: An attacker can easily guess the name and exploit
701   // LLVM.
702 #endif
703   return false;
704 }
705 } // end llvm namespace