Remove PathWithStatus.
[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 Path::Path(StringRef p)
85   : path(p) {}
86
87 Path::Path(const char *StrStart, unsigned StrLen)
88   : path(StrStart, StrLen) {}
89
90 Path&
91 Path::operator=(StringRef that) {
92   path.assign(that.data(), that.size());
93   return *this;
94 }
95
96 bool
97 Path::isValid() const {
98   // Empty paths are considered invalid here.
99   // This code doesn't check MAXPATHLEN because there's no need. Nothing in
100   // LLVM manipulates Paths with fixed-sizes arrays, and if the OS can't
101   // handle names longer than some limit, it'll report this on demand using
102   // ENAMETOLONG.
103   return !path.empty();
104 }
105
106 Path
107 Path::GetTemporaryDirectory(std::string *ErrMsg) {
108 #if defined(HAVE_MKDTEMP)
109   // The best way is with mkdtemp but that's not available on many systems,
110   // Linux and FreeBSD have it. Others probably won't.
111   char pathname[] = "/tmp/llvm_XXXXXX";
112   if (0 == mkdtemp(pathname)) {
113     MakeErrMsg(ErrMsg,
114                std::string(pathname) + ": can't create temporary directory");
115     return Path();
116   }
117   return Path(pathname);
118 #elif defined(HAVE_MKSTEMP)
119   // If no mkdtemp is available, mkstemp can be used to create a temporary file
120   // which is then removed and created as a directory. We prefer this over
121   // mktemp because of mktemp's inherent security and threading risks. We still
122   // have a slight race condition from the time the temporary file is created to
123   // the time it is re-created as a directoy.
124   char pathname[] = "/tmp/llvm_XXXXXX";
125   int fd = 0;
126   if (-1 == (fd = mkstemp(pathname))) {
127     MakeErrMsg(ErrMsg,
128       std::string(pathname) + ": can't create temporary directory");
129     return Path();
130   }
131   ::close(fd);
132   ::unlink(pathname); // start race condition, ignore errors
133   if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
134     MakeErrMsg(ErrMsg,
135       std::string(pathname) + ": can't create temporary directory");
136     return Path();
137   }
138   return Path(pathname);
139 #elif defined(HAVE_MKTEMP)
140   // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
141   // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
142   // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
143   // the XXXXXX with the pid of the process and a letter. That leads to only
144   // twenty six temporary files that can be generated.
145   char pathname[] = "/tmp/llvm_XXXXXX";
146   char *TmpName = ::mktemp(pathname);
147   if (TmpName == 0) {
148     MakeErrMsg(ErrMsg,
149       std::string(TmpName) + ": can't create unique directory name");
150     return Path();
151   }
152   if (-1 == ::mkdir(TmpName, S_IRWXU)) {
153     MakeErrMsg(ErrMsg,
154         std::string(TmpName) + ": can't create temporary directory");
155     return Path();
156   }
157   return Path(TmpName);
158 #else
159   // This is the worst case implementation. tempnam(3) leaks memory unless its
160   // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
161   // issues. The mktemp(3) function doesn't have enough variability in the
162   // temporary name generated. So, we provide our own implementation that
163   // increments an integer from a random number seeded by the current time. This
164   // should be sufficiently unique that we don't have many collisions between
165   // processes. Generally LLVM processes don't run very long and don't use very
166   // many temporary files so this shouldn't be a big issue for LLVM.
167   static time_t num = ::time(0);
168   char pathname[MAXPATHLEN];
169   do {
170     num++;
171     sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
172   } while ( 0 == access(pathname, F_OK ) );
173   if (-1 == ::mkdir(pathname, S_IRWXU)) {
174     MakeErrMsg(ErrMsg,
175       std::string(pathname) + ": can't create temporary directory");
176     return Path();
177   }
178   return Path(pathname);
179 #endif
180 }
181
182 Path
183 Path::GetCurrentDirectory() {
184   char pathname[MAXPATHLEN];
185   if (!getcwd(pathname, MAXPATHLEN)) {
186     assert(false && "Could not query current working directory.");
187     return Path();
188   }
189
190   return Path(pathname);
191 }
192
193 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
194     defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
195     defined(__linux__) || defined(__CYGWIN__)
196 static int
197 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
198     const char *dir, const char *bin)
199 {
200   struct stat sb;
201
202   snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
203   if (realpath(buf, ret) == NULL)
204     return (1);
205   if (stat(buf, &sb) != 0)
206     return (1);
207
208   return (0);
209 }
210
211 static char *
212 getprogpath(char ret[PATH_MAX], const char *bin)
213 {
214   char *pv, *s, *t, buf[PATH_MAX];
215
216   /* First approach: absolute path. */
217   if (bin[0] == '/') {
218     if (test_dir(buf, ret, "/", bin) == 0)
219       return (ret);
220     return (NULL);
221   }
222
223   /* Second approach: relative path. */
224   if (strchr(bin, '/') != NULL) {
225     if (getcwd(buf, PATH_MAX) == NULL)
226       return (NULL);
227     if (test_dir(buf, ret, buf, bin) == 0)
228       return (ret);
229     return (NULL);
230   }
231
232   /* Third approach: $PATH */
233   if ((pv = getenv("PATH")) == NULL)
234     return (NULL);
235   s = pv = strdup(pv);
236   if (pv == NULL)
237     return (NULL);
238   while ((t = strsep(&s, ":")) != NULL) {
239     if (test_dir(buf, ret, t, bin) == 0) {
240       free(pv);
241       return (ret);
242     }
243   }
244   free(pv);
245   return (NULL);
246 }
247 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
248
249 /// GetMainExecutable - Return the path to the main executable, given the
250 /// value of argv[0] from program startup.
251 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
252 #if defined(__APPLE__)
253   // On OS X the executable path is saved to the stack by dyld. Reading it
254   // from there is much faster than calling dladdr, especially for large
255   // binaries with symbols.
256   char exe_path[MAXPATHLEN];
257   uint32_t size = sizeof(exe_path);
258   if (_NSGetExecutablePath(exe_path, &size) == 0) {
259     char link_path[MAXPATHLEN];
260     if (realpath(exe_path, link_path))
261       return Path(link_path);
262   }
263 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
264       defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__)
265   char exe_path[PATH_MAX];
266
267   if (getprogpath(exe_path, argv0) != NULL)
268     return Path(exe_path);
269 #elif defined(__linux__) || defined(__CYGWIN__)
270   char exe_path[MAXPATHLEN];
271   StringRef aPath("/proc/self/exe");
272   if (sys::fs::exists(aPath)) {
273       // /proc is not always mounted under Linux (chroot for example).
274       ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
275       if (len >= 0)
276           return Path(StringRef(exe_path, len));
277   } else {
278       // Fall back to the classical detection.
279       if (getprogpath(exe_path, argv0) != NULL)
280           return Path(exe_path);
281   }
282 #elif defined(HAVE_DLFCN_H)
283   // Use dladdr to get executable path if available.
284   Dl_info DLInfo;
285   int err = dladdr(MainAddr, &DLInfo);
286   if (err == 0)
287     return Path();
288
289   // If the filename is a symlink, we need to resolve and return the location of
290   // the actual executable.
291   char link_path[MAXPATHLEN];
292   if (realpath(DLInfo.dli_fname, link_path))
293     return Path(link_path);
294 #else
295 #error GetMainExecutable is not implemented on this host yet.
296 #endif
297   return Path();
298 }
299
300 bool
301 Path::exists() const {
302   return 0 == access(path.c_str(), F_OK );
303 }
304
305 bool
306 Path::isDirectory() const {
307   struct stat buf;
308   if (0 != stat(path.c_str(), &buf))
309     return false;
310   return ((buf.st_mode & S_IFMT) == S_IFDIR) ? true : false;
311 }
312
313 bool
314 Path::isSymLink() const {
315   struct stat buf;
316   if (0 != lstat(path.c_str(), &buf))
317     return false;
318   return S_ISLNK(buf.st_mode);
319 }
320
321 bool
322 Path::isRegularFile() const {
323   // Get the status so we can determine if it's a file or directory
324   struct stat buf;
325
326   if (0 != stat(path.c_str(), &buf))
327     return false;
328
329   if (S_ISREG(buf.st_mode))
330     return true;
331
332   return false;
333 }
334
335 static bool AddPermissionBits(const Path &File, int bits) {
336   // Get the umask value from the operating system.  We want to use it
337   // when changing the file's permissions. Since calling umask() sets
338   // the umask and returns its old value, we must call it a second
339   // time to reset it to the user's preference.
340   int mask = umask(0777); // The arg. to umask is arbitrary.
341   umask(mask);            // Restore the umask.
342
343   // Get the file's current mode.
344   struct stat buf;
345   if (0 != stat(File.c_str(), &buf))
346     return false;
347   // Change the file to have whichever permissions bits from 'bits'
348   // that the umask would not disable.
349   if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
350       return false;
351   return true;
352 }
353
354 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
355   if (!AddPermissionBits(*this, 0444))
356     return MakeErrMsg(ErrMsg, path + ": can't make file readable");
357   return false;
358 }
359
360 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
361   if (!AddPermissionBits(*this, 0222))
362     return MakeErrMsg(ErrMsg, path + ": can't make file writable");
363   return false;
364 }
365
366 bool
367 Path::set(StringRef a_path) {
368   if (a_path.empty())
369     return false;
370   path = a_path;
371   return true;
372 }
373
374 bool
375 Path::appendComponent(StringRef name) {
376   if (name.empty())
377     return false;
378   if (!lastIsSlash(path))
379     path += '/';
380   path += name;
381   return true;
382 }
383
384 bool
385 Path::eraseComponent() {
386   size_t slashpos = path.rfind('/',path.size());
387   if (slashpos == 0 || slashpos == std::string::npos) {
388     path.erase();
389     return true;
390   }
391   if (slashpos == path.size() - 1)
392     slashpos = path.rfind('/',slashpos-1);
393   if (slashpos == std::string::npos) {
394     path.erase();
395     return true;
396   }
397   path.erase(slashpos);
398   return true;
399 }
400
401 bool
402 Path::eraseSuffix() {
403   size_t dotpos = path.rfind('.',path.size());
404   size_t slashpos = path.rfind('/',path.size());
405   if (dotpos != std::string::npos) {
406     if (slashpos == std::string::npos || dotpos > slashpos+1) {
407       path.erase(dotpos, path.size()-dotpos);
408       return true;
409     }
410   }
411   return false;
412 }
413
414 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
415
416   if (access(beg, R_OK | W_OK) == 0)
417     return false;
418
419   if (create_parents) {
420
421     char* c = end;
422
423     for (; c != beg; --c)
424       if (*c == '/') {
425
426         // Recurse to handling the parent directory.
427         *c = '\0';
428         bool x = createDirectoryHelper(beg, c, create_parents);
429         *c = '/';
430
431         // Return if we encountered an error.
432         if (x)
433           return true;
434
435         break;
436       }
437   }
438
439   return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
440 }
441
442 bool
443 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
444   // Get a writeable copy of the path name
445   std::string pathname(path);
446
447   // Null-terminate the last component
448   size_t lastchar = path.length() - 1 ;
449
450   if (pathname[lastchar] != '/')
451     ++lastchar;
452
453   pathname[lastchar] = '\0';
454
455   if (createDirectoryHelper(&pathname[0], &pathname[lastchar], create_parents))
456     return MakeErrMsg(ErrMsg, pathname + ": can't create directory");
457
458   return false;
459 }
460
461 bool
462 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
463   // Make this into a unique file name
464   if (makeUnique( reuse_current, ErrMsg ))
465     return true;
466
467   // create the file
468   int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
469   if (fd < 0)
470     return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
471   ::close(fd);
472   return false;
473 }
474
475 bool
476 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
477   // Get the status so we can determine if it's a file or directory.
478   struct stat buf;
479   if (0 != stat(path.c_str(), &buf)) {
480     MakeErrMsg(ErrStr, path + ": can't get status of file");
481     return true;
482   }
483
484   // Note: this check catches strange situations. In all cases, LLVM should
485   // only be involved in the creation and deletion of regular files.  This
486   // check ensures that what we're trying to erase is a regular file. It
487   // effectively prevents LLVM from erasing things like /dev/null, any block
488   // special file, or other things that aren't "regular" files.
489   if (S_ISREG(buf.st_mode)) {
490     if (unlink(path.c_str()) != 0)
491       return MakeErrMsg(ErrStr, path + ": can't destroy file");
492     return false;
493   }
494
495   if (!S_ISDIR(buf.st_mode)) {
496     if (ErrStr) *ErrStr = "not a file or directory";
497     return true;
498   }
499
500   if (remove_contents) {
501     // Recursively descend the directory to remove its contents.
502     std::string cmd = "/bin/rm -rf " + path;
503     if (system(cmd.c_str()) != 0) {
504       MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
505       return true;
506     }
507     return false;
508   }
509
510   // Otherwise, try to just remove the one directory.
511   std::string pathname(path);
512   size_t lastchar = path.length() - 1;
513   if (pathname[lastchar] == '/')
514     pathname[lastchar] = '\0';
515   else
516     pathname[lastchar+1] = '\0';
517
518   if (rmdir(pathname.c_str()) != 0)
519     return MakeErrMsg(ErrStr, pathname + ": can't erase directory");
520   return false;
521 }
522
523 bool
524 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
525   if (0 != ::rename(path.c_str(), newName.c_str()))
526     return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
527                newName.str() + "'");
528   return false;
529 }
530
531 bool
532 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
533   struct utimbuf utb;
534   utb.actime = si.modTime.toPosixTime();
535   utb.modtime = utb.actime;
536   if (0 != ::utime(path.c_str(),&utb))
537     return MakeErrMsg(ErrStr, path + ": can't set file modification time");
538   if (0 != ::chmod(path.c_str(),si.mode))
539     return MakeErrMsg(ErrStr, path + ": can't set mode");
540   return false;
541 }
542
543 bool
544 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
545   bool Exists;
546   if (reuse_current && (fs::exists(path, Exists) || !Exists))
547     return false; // File doesn't exist already, just use it!
548
549   // Append an XXXXXX pattern to the end of the file for use with mkstemp,
550   // mktemp or our own implementation.
551   // This uses std::vector instead of SmallVector to avoid a dependence on
552   // libSupport. And performance isn't critical here.
553   std::vector<char> Buf;
554   Buf.resize(path.size()+8);
555   char *FNBuffer = &Buf[0];
556     path.copy(FNBuffer,path.size());
557   bool isdir;
558   if (!fs::is_directory(path, isdir) && isdir)
559     strcpy(FNBuffer+path.size(), "/XXXXXX");
560   else
561     strcpy(FNBuffer+path.size(), "-XXXXXX");
562
563 #if defined(HAVE_MKSTEMP)
564   int TempFD;
565   if ((TempFD = mkstemp(FNBuffer)) == -1)
566     return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
567
568   // We don't need to hold the temp file descriptor... we will trust that no one
569   // will overwrite/delete the file before we can open it again.
570   close(TempFD);
571
572   // Save the name
573   path = FNBuffer;
574
575   // By default mkstemp sets the mode to 0600, so update mode bits now.
576   AddPermissionBits (*this, 0666);
577 #elif defined(HAVE_MKTEMP)
578   // If we don't have mkstemp, use the old and obsolete mktemp function.
579   if (mktemp(FNBuffer) == 0)
580     return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
581
582   // Save the name
583   path = FNBuffer;
584 #else
585   // Okay, looks like we have to do it all by our lonesome.
586   static unsigned FCounter = 0;
587   // Try to initialize with unique value.
588   if (FCounter == 0) FCounter = ((unsigned)getpid() & 0xFFFF) << 8;
589   char* pos = strstr(FNBuffer, "XXXXXX");
590   do {
591     if (++FCounter > 0xFFFFFF) {
592       return MakeErrMsg(ErrMsg,
593         path + ": can't make unique filename: too many files");
594     }
595     sprintf(pos, "%06X", FCounter);
596     path = FNBuffer;
597   } while (exists());
598   // POSSIBLE SECURITY BUG: An attacker can easily guess the name and exploit
599   // LLVM.
600 #endif
601   return false;
602 }
603 } // end llvm namespace