For PR495:
[oota-llvm.git] / lib / System / Unix / Path.inc
1 //===- llvm/System/Unix/Path.cpp - Unix Path Implementation -----*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Reid Spencer and is distributed under the 
6 // University of Illinois Open Source 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 "llvm/Config/alloca.h"
20 #include "Unix.h"
21 #if HAVE_SYS_STAT_H
22 #include <sys/stat.h>
23 #endif
24 #if HAVE_FCNTL_H
25 #include <fcntl.h>
26 #endif
27 #if HAVE_UTIME_H
28 #include <utime.h>
29 #endif
30 #if HAVE_TIME_H
31 #include <time.h>
32 #endif
33 #if HAVE_DIRENT_H
34 # include <dirent.h>
35 # define NAMLEN(dirent) strlen((dirent)->d_name)
36 #else
37 # define dirent direct
38 # define NAMLEN(dirent) (dirent)->d_namlen
39 # if HAVE_SYS_NDIR_H
40 #  include <sys/ndir.h>
41 # endif
42 # if HAVE_SYS_DIR_H
43 #  include <sys/dir.h>
44 # endif
45 # if HAVE_NDIR_H
46 #  include <ndir.h>
47 # endif
48 #endif
49
50 // Put in a hack for Cygwin which falsely reports that the mkdtemp function
51 // is available when it is not.
52 #ifdef __CYGWIN__
53 # undef HAVE_MKDTEMP
54 #endif
55
56 namespace llvm {
57 using namespace sys;
58
59 Path::Path(const std::string& unverified_path) : path(unverified_path) {
60   if (unverified_path.empty())
61     return;
62   if (this->isValid()) 
63     return;
64   // oops, not valid.
65   path.clear();
66   ThrowErrno(unverified_path + ": path is not valid");
67 }
68
69 bool 
70 Path::isValid() const {
71   if (path.empty()) 
72     return false;
73   else if (path.length() >= MAXPATHLEN)
74     return false;
75 #if defined(HAVE_REALPATH)
76   char pathname[MAXPATHLEN];
77   if (0 == realpath(path.c_str(), pathname))
78     if (errno != EACCES && errno != EIO && errno != ENOENT && errno != ENOTDIR)
79       return false;
80 #endif
81   return true;
82 }
83
84 Path
85 Path::GetRootDirectory() {
86   Path result;
87   result.set("/");
88   return result;
89 }
90
91 Path
92 Path::GetTemporaryDirectory() {
93 #if defined(HAVE_MKDTEMP)
94   // The best way is with mkdtemp but that's not available on many systems, 
95   // Linux and FreeBSD have it. Others probably won't.
96   char pathname[MAXPATHLEN];
97   strcpy(pathname,"/tmp/llvm_XXXXXX");
98   if (0 == mkdtemp(pathname))
99     ThrowErrno(std::string(pathname) + ": can't create temporary directory");
100   Path result;
101   result.set(pathname);
102   assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
103   return result;
104 #elif defined(HAVE_MKSTEMP)
105   // If no mkdtemp is available, mkstemp can be used to create a temporary file
106   // which is then removed and created as a directory. We prefer this over
107   // mktemp because of mktemp's inherent security and threading risks. We still
108   // have a slight race condition from the time the temporary file is created to
109   // the time it is re-created as a directoy. 
110   char pathname[MAXPATHLEN];
111   strcpy(pathname, "/tmp/llvm_XXXXXX");
112   int fd = 0;
113   if (-1 == (fd = mkstemp(pathname)))
114     ThrowErrno(std::string(pathname) + ": can't create temporary directory");
115   ::close(fd);
116   ::unlink(pathname); // start race condition, ignore errors
117   if (-1 == ::mkdir(pathname, S_IRWXU)) // end race condition
118     ThrowErrno(std::string(pathname) + ": can't create temporary directory");
119   Path result;
120   result.set(pathname);
121   assert(result.isValid() && "mkstemp didn't create a valid pathname!");
122   return result;
123 #elif defined(HAVE_MKTEMP)
124   // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
125   // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
126   // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
127   // the XXXXXX with the pid of the process and a letter. That leads to only
128   // twenty six temporary files that can be generated.
129   char pathname[MAXPATHLEN];
130   strcpy(pathname, "/tmp/llvm_XXXXXX");
131   char *TmpName = ::mktemp(pathname);
132   if (TmpName == 0)
133     ThrowErrno(std::string(TmpName) + ": can't create unique directory name");
134   if (-1 == ::mkdir(TmpName, S_IRWXU))
135     ThrowErrno(std::string(TmpName) + ": can't create temporary directory");
136   Path result;
137   result.set(TmpName);
138   assert(result.isValid() && "mktemp didn't create a valid pathname!");
139   return result;
140 #else
141   // This is the worst case implementation. tempnam(3) leaks memory unless its
142   // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
143   // issues. The mktemp(3) function doesn't have enough variability in the
144   // temporary name generated. So, we provide our own implementation that 
145   // increments an integer from a random number seeded by the current time. This
146   // should be sufficiently unique that we don't have many collisions between
147   // processes. Generally LLVM processes don't run very long and don't use very
148   // many temporary files so this shouldn't be a big issue for LLVM.
149   static time_t num = ::time(0);
150   char pathname[MAXPATHLEN];
151   do {
152     num++;
153     sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
154   } while ( 0 == access(pathname, F_OK ) );
155   if (-1 == ::mkdir(pathname, S_IRWXU))
156     ThrowErrno(std::string(pathname) + ": can't create temporary directory");
157   Path result;
158   result.set(pathname);
159   assert(result.isValid() && "mkstemp didn't create a valid pathname!");
160   return result;
161 #endif
162 }
163
164 static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
165   const char* at = path;
166   const char* delim = strchr(at, ':');
167   Path tmpPath;
168   while( delim != 0 ) {
169     std::string tmp(at, size_t(delim-at));
170     if (tmpPath.set(tmp))
171       if (tmpPath.canRead())
172         Paths.push_back(tmpPath);
173     at = delim + 1;
174     delim = strchr(at, ':');
175   }
176   if (*at != 0)
177     if (tmpPath.set(std::string(at)))
178       if (tmpPath.canRead())
179         Paths.push_back(tmpPath);
180
181 }
182
183 void 
184 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
185 #ifdef LTDL_SHLIBPATH_VAR
186   char* env_var = getenv(LTDL_SHLIBPATH_VAR);
187   if (env_var != 0) {
188     getPathList(env_var,Paths);
189   }
190 #endif
191   // FIXME: Should this look at LD_LIBRARY_PATH too?
192   Paths.push_back(sys::Path("/usr/local/lib/"));
193   Paths.push_back(sys::Path("/usr/X11R6/lib/"));
194   Paths.push_back(sys::Path("/usr/lib/"));
195   Paths.push_back(sys::Path("/lib/"));
196 }
197
198 void
199 Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
200   char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
201   if (env_var != 0) {
202     getPathList(env_var,Paths);
203   }
204 #ifdef LLVM_LIBDIR
205   {
206     Path tmpPath;
207     if (tmpPath.set(LLVM_LIBDIR))
208       if (tmpPath.canRead())
209         Paths.push_back(tmpPath);
210   }
211 #endif
212   GetSystemLibraryPaths(Paths);
213 }
214
215 Path 
216 Path::GetLLVMDefaultConfigDir() {
217   return Path("/etc/llvm/");
218 }
219
220 Path
221 Path::GetUserHomeDirectory() {
222   const char* home = getenv("HOME");
223   if (home) {
224     Path result;
225     if (result.set(home))
226       return result;
227   }
228   return GetRootDirectory();
229 }
230
231 bool
232 Path::isFile() const {
233   struct stat buf;
234   if (0 != stat(path.c_str(), &buf)) {
235     ThrowErrno(path + ": can't determine type of path object: ");
236   }
237   return S_ISREG(buf.st_mode);
238 }
239
240 bool
241 Path::isDirectory() const {
242   struct stat buf;
243   if (0 != stat(path.c_str(), &buf)) {
244     ThrowErrno(path + ": can't determine type of path object: ");
245   }
246   return S_ISDIR(buf.st_mode);
247 }
248
249 std::string
250 Path::getBasename() const {
251   // Find the last slash
252   size_t slash = path.rfind('/');
253   if (slash == std::string::npos)
254     slash = 0;
255   else
256     slash++;
257
258   return path.substr(slash, path.rfind('.'));
259 }
260
261 bool Path::hasMagicNumber(const std::string &Magic) const {
262   size_t len = Magic.size();
263   assert(len < 1024 && "Request for magic string too long");
264   char* buf = (char*) alloca(1 + len);
265   int fd = ::open(path.c_str(),O_RDONLY);
266   if (fd < 0)
267     return false;
268   size_t read_len = ::read(fd, buf, len);
269   close(fd);
270   if (len != read_len)
271     return false;
272   buf[len] = '\0';
273   return Magic == buf;
274 }
275
276 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
277   if (!isFile())
278     return false;
279   assert(len < 1024 && "Request for magic string too long");
280   char* buf = (char*) alloca(1 + len);
281   int fd = ::open(path.c_str(),O_RDONLY);
282   if (fd < 0)
283     return false;
284   ssize_t bytes_read = ::read(fd, buf, len);
285   ::close(fd);
286   if (ssize_t(len) != bytes_read) {
287     Magic.clear();
288     return false;
289   }
290   Magic.assign(buf,len);
291   return true;
292 }
293
294 bool 
295 Path::isBytecodeFile() const {
296   char buffer[ 4];
297   buffer[0] = 0;
298   int fd = ::open(path.c_str(),O_RDONLY);
299   if (fd < 0)
300     return false;
301   ssize_t bytes_read = ::read(fd, buffer, 4);
302   ::close(fd);
303   if (4 != bytes_read) 
304     return false;
305
306   return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
307       (buffer[3] == 'c' || buffer[3] == 'm'));
308 }
309
310 bool
311 Path::exists() const {
312   return 0 == access(path.c_str(), F_OK );
313 }
314
315 bool
316 Path::canRead() const {
317   return 0 == access(path.c_str(), F_OK | R_OK );
318 }
319
320 bool
321 Path::canWrite() const {
322   return 0 == access(path.c_str(), F_OK | W_OK );
323 }
324
325 bool
326 Path::canExecute() const {
327   struct stat st;
328   int r = stat(path.c_str(), &st);
329   if (r != 0 || !S_ISREG(st.st_mode))
330     return false;
331   return 0 == access(path.c_str(), R_OK | X_OK );
332 }
333
334 std::string 
335 Path::getLast() const {
336   // Find the last slash
337   size_t pos = path.rfind('/');
338
339   // Handle the corner cases
340   if (pos == std::string::npos)
341     return path;
342
343   // If the last character is a slash
344   if (pos == path.length()-1) {
345     // Find the second to last slash
346     size_t pos2 = path.rfind('/', pos-1);
347     if (pos2 == std::string::npos)
348       return path.substr(0,pos);
349     else
350       return path.substr(pos2+1,pos-pos2-1);
351   }
352   // Return everything after the last slash
353   return path.substr(pos+1);
354 }
355
356 void
357 Path::getStatusInfo(StatusInfo& info) const {
358   struct stat buf;
359   if (0 != stat(path.c_str(), &buf)) {
360     ThrowErrno(path + ": can't determine type of path object: ");
361   }
362   info.fileSize = buf.st_size;
363   info.modTime.fromEpochTime(buf.st_mtime);
364   info.mode = buf.st_mode;
365   info.user = buf.st_uid;
366   info.group = buf.st_gid;
367   info.isDir = S_ISDIR(buf.st_mode);
368 }
369
370 static bool AddPermissionBits(const std::string& Filename, int bits) {
371   // Get the umask value from the operating system.  We want to use it
372   // when changing the file's permissions. Since calling umask() sets
373   // the umask and returns its old value, we must call it a second
374   // time to reset it to the user's preference.
375   int mask = umask(0777); // The arg. to umask is arbitrary.
376   umask(mask);            // Restore the umask.
377
378   // Get the file's current mode.
379   struct stat st;
380   if ((stat(Filename.c_str(), &st)) == -1)
381     return false;
382
383   // Change the file to have whichever permissions bits from 'bits'
384   // that the umask would not disable.
385   if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)
386     return false;
387
388   return true;
389 }
390
391 void Path::makeReadable() {
392   if (!AddPermissionBits(path,0444))
393     ThrowErrno(path + ": can't make file readable");
394 }
395
396 void Path::makeWriteable() {
397   if (!AddPermissionBits(path,0222))
398     ThrowErrno(path + ": can't make file writable");
399 }
400
401 void Path::makeExecutable() {
402   if (!AddPermissionBits(path,0111))
403     ThrowErrno(path + ": can't make file executable");
404 }
405
406 bool
407 Path::getDirectoryContents(std::set<Path>& result) const {
408   if (!isDirectory())
409     return false;
410   DIR* direntries = ::opendir(path.c_str());
411   if (direntries == 0)
412     ThrowErrno(path + ": can't open directory");
413
414   result.clear();
415   struct dirent* de = ::readdir(direntries);
416   for ( ; de != 0; de = ::readdir(direntries)) {
417     if (de->d_name[0] != '.') {
418       Path aPath(path + (const char*)de->d_name);
419       struct stat buf;
420       if (0 != stat(aPath.path.c_str(), &buf)) {
421         int stat_errno = errno;
422         struct stat st;
423         if (0 == lstat(aPath.path.c_str(), &st) && S_ISLNK(st.st_mode))
424           continue; // dangling symlink -- ignore
425         ThrowErrno(aPath.path + 
426           ": can't determine file object type", stat_errno);
427       }
428       result.insert(aPath);
429     }
430   }
431   
432   closedir(direntries);
433   return true;
434 }
435
436 bool
437 Path::set(const std::string& a_path) {
438   if (a_path.empty())
439     return false;
440   std::string save(path);
441   path = a_path;
442   if (!isValid()) {
443     path = save;
444     return false;
445   }
446   return true;
447 }
448
449 bool
450 Path::appendComponent(const std::string& name) {
451   if (name.empty())
452     return false;
453   std::string save(path);
454   if (!path.empty()) {
455     size_t last = path.size() - 1;
456     if (path[last] != '/') 
457       path += '/';
458   }
459   path += name;
460   if (!isValid()) {
461     path = save;
462     return false;
463   }
464   return true;
465 }
466
467 bool
468 Path::eraseComponent() {
469   size_t slashpos = path.rfind('/',path.size());
470   if (slashpos == 0 || slashpos == std::string::npos) {
471     path.erase();
472     return true;
473   }
474   if (slashpos == path.size() - 1)
475     slashpos = path.rfind('/',slashpos-1);
476   if (slashpos == std::string::npos) {
477     path.erase();
478     return true;
479   }
480   path.erase(slashpos);
481   return true;
482 }
483
484 bool
485 Path::appendSuffix(const std::string& suffix) {
486   std::string save(path);
487   path.append(".");
488   path.append(suffix);
489   if (!isValid()) {
490     path = save;
491     return false;
492   }
493   return true;
494 }
495
496 bool
497 Path::eraseSuffix() {
498   std::string save(path);
499   size_t dotpos = path.rfind('.',path.size());
500   size_t slashpos = path.rfind('/',path.size());
501   if (slashpos != std::string::npos && 
502       dotpos != std::string::npos &&
503       dotpos > slashpos) {
504     path.erase(dotpos, path.size()-dotpos);
505   }
506   if (!isValid()) {
507     path = save;
508     return false;
509   }
510   return true;
511 }
512
513 bool
514 Path::createDirectory( bool create_parents) {
515   // Get a writeable copy of the path name
516   char pathname[MAXPATHLEN];
517   path.copy(pathname,MAXPATHLEN);
518
519   // Null-terminate the last component
520   int lastchar = path.length() - 1 ; 
521   if (pathname[lastchar] == '/') 
522     pathname[lastchar] = 0;
523   else 
524     pathname[lastchar+1] = 0;
525
526   // If we're supposed to create intermediate directories
527   if ( create_parents ) {
528     // Find the end of the initial name component
529     char * next = strchr(pathname,'/');
530     if ( pathname[0] == '/') 
531       next = strchr(&pathname[1],'/');
532
533     // Loop through the directory components until we're done 
534     while ( next != 0 ) {
535       *next = 0;
536       if (0 != access(pathname, F_OK | R_OK | W_OK))
537         if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
538           ThrowErrno(std::string(pathname) + ": can't create directory");
539       char* save = next;
540       next = strchr(next+1,'/');
541       *save = '/';
542     }
543   } 
544
545   if (0 != access(pathname, F_OK | R_OK))
546     if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
547       ThrowErrno(std::string(pathname) + ": can't create directory");
548   return true;
549 }
550
551 bool
552 Path::createFile() {
553   // Create the file
554   int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
555   if (fd < 0)
556     ThrowErrno(path + ": can't create file");
557   ::close(fd);
558
559   return true;
560 }
561
562 bool
563 Path::createTemporaryFile(bool reuse_current) {
564   // Make this into a unique file name
565   makeUnique( reuse_current );
566
567   // create the file
568   int outFile = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
569   if (outFile != -1) {
570     ::close(outFile);
571     return true;
572   }
573   return false;
574 }
575
576 bool
577 Path::destroy(bool remove_contents) const {
578   // Make sure we're dealing with a directory
579   if (isFile()) {
580     if (0 != unlink(path.c_str()))
581       ThrowErrno(path + ": can't destroy file");
582   } else if (isDirectory()) {
583     if (remove_contents) {
584       // Recursively descend the directory to remove its content
585       std::string cmd("/bin/rm -rf ");
586       cmd += path;
587       system(cmd.c_str());
588     } else {
589       // Otherwise, try to just remove the one directory
590       char pathname[MAXPATHLEN];
591       path.copy(pathname,MAXPATHLEN);
592       int lastchar = path.length() - 1 ; 
593       if (pathname[lastchar] == '/') 
594         pathname[lastchar] = 0;
595       else
596         pathname[lastchar+1] = 0;
597       if ( 0 != rmdir(pathname))
598         ThrowErrno(std::string(pathname) + ": can't destroy directory");
599     }
600   }
601   else
602     return false;
603   return true;
604 }
605
606 bool
607 Path::rename(const Path& newName) {
608   if (0 != ::rename(path.c_str(), newName.c_str()))
609     ThrowErrno(std::string("can't rename '") + path + "' as '" + 
610                newName.toString() + "' ");
611   return true;
612 }
613
614 bool
615 Path::setStatusInfo(const StatusInfo& si) const {
616   struct utimbuf utb;
617   utb.actime = si.modTime.toPosixTime();
618   utb.modtime = utb.actime;
619   if (0 != ::utime(path.c_str(),&utb))
620     ThrowErrno(path + ": can't set file modification time");
621   if (0 != ::chmod(path.c_str(),si.mode))
622     ThrowErrno(path + ": can't set mode");
623   return true;
624 }
625
626 void 
627 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src) {
628   int inFile = -1;
629   int outFile = -1;
630   try {
631     inFile = ::open(Src.c_str(), O_RDONLY);
632     if (inFile == -1)
633       ThrowErrno(Src.toString() + ": can't open source file to copy: ");
634
635     outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
636     if (outFile == -1)
637       ThrowErrno(Dest.toString() +": can't create destination file for copy: ");
638
639     char Buffer[16*1024];
640     while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
641       if (Amt == -1) {
642         if (errno != EINTR && errno != EAGAIN) 
643           ThrowErrno(Src.toString()+": can't read source file: ");
644       } else {
645         char *BufPtr = Buffer;
646         while (Amt) {
647           ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
648           if (AmtWritten == -1) {
649             if (errno != EINTR && errno != EAGAIN) 
650               ThrowErrno(Dest.toString() + ": can't write destination file: ");
651           } else {
652             Amt -= AmtWritten;
653             BufPtr += AmtWritten;
654           }
655         }
656       }
657     }
658     ::close(inFile);
659     ::close(outFile);
660   } catch (...) {
661     if (inFile != -1)
662       ::close(inFile);
663     if (outFile != -1)
664       ::close(outFile);
665     throw;
666   }
667 }
668
669 void 
670 Path::makeUnique(bool reuse_current) {
671   if (reuse_current && !exists())
672     return; // File doesn't exist already, just use it!
673
674   // Append an XXXXXX pattern to the end of the file for use with mkstemp, 
675   // mktemp or our own implementation.
676   char *FNBuffer = (char*) alloca(path.size()+8);
677   path.copy(FNBuffer,path.size());
678   strcpy(FNBuffer+path.size(), "-XXXXXX");
679
680 #if defined(HAVE_MKSTEMP)
681   int TempFD;
682   if ((TempFD = mkstemp(FNBuffer)) == -1) {
683     ThrowErrno(path + ": can't make unique filename");
684   }
685
686   // We don't need to hold the temp file descriptor... we will trust that no one
687   // will overwrite/delete the file before we can open it again.
688   close(TempFD);
689
690   // Save the name
691   path = FNBuffer;
692 #elif defined(HAVE_MKTEMP)
693   // If we don't have mkstemp, use the old and obsolete mktemp function.
694   if (mktemp(FNBuffer) == 0) {
695     ThrowErrno(path + ": can't make unique filename");
696   }
697
698   // Save the name
699   path = FNBuffer;
700 #else
701   // Okay, looks like we have to do it all by our lonesome.
702   static unsigned FCounter = 0;
703   unsigned offset = path.size() + 1;
704   while ( FCounter < 999999 && exists()) {
705     sprintf(FNBuffer+offset,"%06u",++FCounter);
706     path = FNBuffer;
707   }
708   if (FCounter > 999999)
709     throw std::string(path + ": can't make unique filename: too many files");
710 #endif
711
712 }
713 }
714