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