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