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