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