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