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