* Implement getDirectoryContents * Implement getStatusInfo * Implement setStatusInfo...
[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 "Unix.h"
21 #include <sys/stat.h>
22 #include <fcntl.h>
23 #include <fstream>
24 #include <utime.h>
25 #include <dirent.h>
26
27 namespace llvm {
28 using namespace sys;
29
30 Path::Path(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 inline bool IsLibrary(Path& path, const std::string& basename) {
50   if (path.appendFile(std::string("lib") + basename)) {
51     if (path.appendSuffix(Path::GetDLLSuffix()) && path.readable())
52       return true;
53     else if (path.elideSuffix() && path.appendSuffix("a") && path.readable())
54       return true;
55     else if (path.elideSuffix() && path.appendSuffix("o") && path.readable())
56       return true;
57     else if (path.elideSuffix() && path.appendSuffix("bc") && path.readable())
58       return true;
59   } else if (path.elideFile() && path.appendFile(basename)) {
60     if (path.appendSuffix(Path::GetDLLSuffix()) && path.readable())
61       return true;
62     else if (path.elideSuffix() && path.appendSuffix("a") && path.readable())
63       return true;
64     else if (path.elideSuffix() && path.appendSuffix("o") && path.readable())
65       return true;
66     else if (path.elideSuffix() && path.appendSuffix("bc") && path.readable())
67       return true;
68   }
69   path.clear();
70   return false;
71 }
72
73 Path 
74 Path::GetLibraryPath(const std::string& basename, 
75                      const std::vector<std::string>& LibPaths) {
76   Path result;
77
78   // Try the paths provided
79   for (std::vector<std::string>::const_iterator I = LibPaths.begin(),
80        E = LibPaths.end(); I != E; ++I ) {
81     if (result.setDirectory(*I) && IsLibrary(result,basename))
82       return result;
83   }
84
85   // Try the LLVM lib directory in the LLVM install area
86   if (result.setDirectory(LLVM_LIBDIR) && IsLibrary(result,basename))
87     return result;
88
89   // Try /usr/lib
90   if (result.setDirectory("/usr/lib/") && IsLibrary(result,basename))
91     return result;
92
93   // Try /lib
94   if (result.setDirectory("/lib/") && IsLibrary(result,basename))
95     return result;
96
97   // Can't find it, give up and return invalid path.
98   result.clear();
99   return result;
100 }
101
102 Path 
103 Path::GetSystemLibraryPath1() {
104   return Path("/lib/");
105 }
106
107 Path 
108 Path::GetSystemLibraryPath2() {
109   return Path("/usr/lib/");
110 }
111
112 Path 
113 Path::GetLLVMDefaultConfigDir() {
114   return Path("/etc/llvm/");
115 }
116
117 Path 
118 Path::GetLLVMConfigDir() {
119   Path result;
120   if (result.setDirectory(LLVM_ETCDIR))
121     return result;
122   return GetLLVMDefaultConfigDir();
123 }
124
125 Path
126 Path::GetUserHomeDirectory() {
127   const char* home = getenv("HOME");
128   if (home) {
129     Path result;
130     if (result.setDirectory(home))
131       return result;
132   }
133   return GetRootDirectory();
134 }
135
136 bool
137 Path::isFile() const {
138   return (isValid() && path[path.length()-1] != '/');
139 }
140
141 bool
142 Path::isDirectory() const {
143   return (isValid() && path[path.length()-1] == '/');
144 }
145
146 std::string
147 Path::getBasename() const {
148   // Find the last slash
149   size_t slash = path.rfind('/');
150   if (slash == std::string::npos)
151     slash = 0;
152   else
153     slash++;
154
155   return path.substr(slash, path.rfind('.'));
156 }
157
158 bool Path::hasMagicNumber(const std::string &Magic) const {
159   size_t len = Magic.size();
160   char buf[ 1 + len];
161   std::ifstream f(path.c_str());
162   f.read(buf, len);
163   buf[len] = '\0';
164   f.close();
165   return Magic == buf;
166 }
167
168 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
169   if (!isFile())
170     return false;
171   char buf[1 + len];
172   std::ifstream f(path.c_str());
173   f.read(buf,len);
174   buf[len] = '\0';
175   Magic = buf;
176   return true;
177 }
178
179 bool 
180 Path::isBytecodeFile() const {
181   char buffer[ 4];
182   buffer[0] = 0;
183   std::ifstream f(path.c_str());
184   f.read(buffer, 4);
185   if (f.bad())
186     ThrowErrno("can't read file signature");
187
188   return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
189       (buffer[3] == 'c' || buffer[3] == 'm'));
190 }
191
192 bool
193 Path::isArchive() const {
194   if (readable()) {
195     return hasMagicNumber("!<arch>\012");
196   }
197   return false;
198 }
199
200 bool
201 Path::exists() const {
202   return 0 == access(path.c_str(), F_OK );
203 }
204
205 bool
206 Path::readable() const {
207   return 0 == access(path.c_str(), F_OK | R_OK );
208 }
209
210 bool
211 Path::writable() const {
212   return 0 == access(path.c_str(), F_OK | W_OK );
213 }
214
215 bool
216 Path::executable() const {
217   return 0 == access(path.c_str(), R_OK | X_OK );
218 }
219
220 std::string 
221 Path::getLast() const {
222   // Find the last slash
223   size_t pos = path.rfind('/');
224
225   // Handle the corner cases
226   if (pos == std::string::npos)
227     return path;
228
229   // If the last character is a slash
230   if (pos == path.length()-1) {
231     // Find the second to last slash
232     size_t pos2 = path.rfind('/', pos-1);
233     if (pos2 == std::string::npos)
234       return path.substr(0,pos);
235     else
236       return path.substr(pos2+1,pos-pos2-1);
237   }
238   // Return everything after the last slash
239   return path.substr(pos+1);
240 }
241
242 void
243 Path::getStatusInfo(StatusInfo& info) {
244   struct stat buf;
245   if (0 != stat(path.c_str(), &buf)) {
246     ThrowErrno(std::string("Can't get status: ")+path);
247   }
248   info.fileSize = buf.st_size;
249   info.modTime.fromEpochTime(buf.st_mtime);
250   info.mode = buf.st_mode;
251   info.user = buf.st_uid;
252   info.group = buf.st_gid;
253   info.isDir = S_ISDIR(buf.st_mode);
254   if (info.isDir && path[path.length()-1] != '/')
255     path += '/';
256 }
257
258 bool
259 Path::getDirectoryContents(Vector& result) const {
260   if (!isDirectory())
261     return false;
262   DIR* direntries = ::opendir(path.c_str());
263   if (direntries == 0)
264     ThrowErrno(path + ": can't open directory");
265
266   result.clear();
267   struct dirent* de = ::readdir(direntries);
268   while (de != 0) {
269     if (de->d_name[0] != '.') {
270       Path aPath(path + (const char*)de->d_name);
271       struct stat buf;
272       if (0 != stat(aPath.path.c_str(), &buf))
273         ThrowErrno(aPath.path + ": can't get status");
274       if (S_ISDIR(buf.st_mode))
275         aPath.path += "/";
276       result.push_back(aPath);
277     }
278     de = ::readdir(direntries);
279   }
280   
281   closedir(direntries);
282   return true;
283 }
284
285 bool
286 Path::setDirectory(const std::string& a_path) {
287   if (a_path.size() == 0)
288     return false;
289   Path save(*this);
290   path = a_path;
291   size_t last = a_path.size() -1;
292   if (last != 0 && a_path[last] != '/')
293     path += '/';
294   if (!isValid()) {
295     path = save.path;
296     return false;
297   }
298   return true;
299 }
300
301 bool
302 Path::setFile(const std::string& a_path) {
303   if (a_path.size() == 0)
304     return false;
305   Path save(*this);
306   path = a_path;
307   size_t last = a_path.size() - 1;
308   while (last > 0 && a_path[last] == '/')
309     last--;
310   path.erase(last+1);
311   if (!isValid()) {
312     path = save.path;
313     return false;
314   }
315   return true;
316 }
317
318 bool
319 Path::appendDirectory(const std::string& dir) {
320   if (isFile()) 
321     return false;
322   Path save(*this);
323   path += dir;
324   path += "/";
325   if (!isValid()) {
326     path = save.path;
327     return false;
328   }
329   return true;
330 }
331
332 bool
333 Path::elideDirectory() {
334   if (isFile()) 
335     return false;
336   size_t slashpos = path.rfind('/',path.size());
337   if (slashpos == 0 || slashpos == std::string::npos)
338     return false;
339   if (slashpos == path.size() - 1)
340     slashpos = path.rfind('/',slashpos-1);
341   if (slashpos == std::string::npos)
342     return false;
343   path.erase(slashpos);
344   return true;
345 }
346
347 bool
348 Path::appendFile(const std::string& file) {
349   if (!isDirectory()) 
350     return false;
351   Path save(*this);
352   path += file;
353   if (!isValid()) {
354     path = save.path;
355     return false;
356   }
357   return true;
358 }
359
360 bool
361 Path::elideFile() {
362   if (isDirectory()) 
363     return false;
364   size_t slashpos = path.rfind('/',path.size());
365   if (slashpos == std::string::npos)
366     return false;
367   path.erase(slashpos+1);
368   return true;
369 }
370
371 bool
372 Path::appendSuffix(const std::string& suffix) {
373   if (isDirectory()) 
374     return false;
375   Path save(*this);
376   path.append(".");
377   path.append(suffix);
378   if (!isValid()) {
379     path = save.path;
380     return false;
381   }
382   return true;
383 }
384
385 bool 
386 Path::elideSuffix() {
387   if (isDirectory()) return false;
388   size_t dotpos = path.rfind('.',path.size());
389   size_t slashpos = path.rfind('/',path.size());
390   if (slashpos != std::string::npos && dotpos != std::string::npos &&
391       dotpos > slashpos) {
392     path.erase(dotpos, path.size()-dotpos);
393     return true;
394   }
395   return false;
396 }
397
398
399 bool
400 Path::createDirectory( bool create_parents) {
401   // Make sure we're dealing with a directory
402   if (!isDirectory()) return false;
403
404   // Get a writeable copy of the path name
405   char pathname[MAXPATHLEN];
406   path.copy(pathname,MAXPATHLEN);
407
408   // Null-terminate the last component
409   int lastchar = path.length() - 1 ; 
410   if (pathname[lastchar] == '/') 
411     pathname[lastchar] = 0;
412   else 
413     pathname[lastchar+1] = 0;
414
415   // If we're supposed to create intermediate directories
416   if ( create_parents ) {
417     // Find the end of the initial name component
418     char * next = strchr(pathname,'/');
419     if ( pathname[0] == '/') 
420       next = strchr(&pathname[1],'/');
421
422     // Loop through the directory components until we're done 
423     while ( next != 0 ) {
424       *next = 0;
425       if (0 != access(pathname, F_OK | R_OK | W_OK))
426         if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
427           ThrowErrno(std::string(pathname) + ": Can't create directory");
428       char* save = next;
429       next = strchr(next+1,'/');
430       *save = '/';
431     }
432   } 
433
434   if (0 != access(pathname, F_OK | R_OK))
435     if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
436       ThrowErrno(std::string(pathname) + ": Can't create directory");
437   return true;
438 }
439
440 bool
441 Path::createFile() {
442   // Make sure we're dealing with a file
443   if (!isFile()) return false; 
444
445   // Create the file
446   int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
447   if (fd < 0)
448     ThrowErrno(path + ": Can't create file");
449   ::close(fd);
450
451   return true;
452 }
453
454 bool
455 Path::createTemporaryFile() {
456   // Make sure we're dealing with a file
457   if (!isFile()) return false;
458
459   // Append the filename filler
460   char pathname[MAXPATHLEN];
461   path.copy(pathname,MAXPATHLEN);
462   pathname[path.length()] = 0;
463   strcat(pathname,"XXXXXX");
464   int fd = ::mkstemp(pathname);
465   if (fd < 0) {
466     ThrowErrno(path + ": Can't create temporary file");
467   }
468   path = pathname;
469   ::close(fd);
470   return true;
471 }
472
473 bool
474 Path::destroyDirectory(bool remove_contents) {
475   // Make sure we're dealing with a directory
476   if (!isDirectory()) return false;
477
478   // If it doesn't exist, we're done.
479   if (!exists()) return true;
480
481   if (remove_contents) {
482     // Recursively descend the directory to remove its content
483     std::string cmd("/bin/rm -rf ");
484     cmd += path;
485     system(cmd.c_str());
486   } else {
487     // Otherwise, try to just remove the one directory
488     char pathname[MAXPATHLEN];
489     path.copy(pathname,MAXPATHLEN);
490     int lastchar = path.length() - 1 ; 
491     if (pathname[lastchar] == '/') 
492       pathname[lastchar] = 0;
493     else
494       pathname[lastchar+1] = 0;
495     if ( 0 != rmdir(pathname))
496       ThrowErrno(std::string(pathname) + ": Can't destroy directory");
497   }
498   return true;
499 }
500
501 bool
502 Path::destroyFile() {
503   if (!isFile()) return false;
504   if (0 != unlink(path.c_str()))
505     ThrowErrno(path + ": Can't destroy file");
506   return true;
507 }
508
509 bool
510 Path::renameFile(const Path& newName) {
511   if (!isFile()) return false;
512   if (0 != rename(path.c_str(), newName.c_str()))
513     ThrowErrno(std::string("can't rename ") + path + " as " + newName.get());
514   return true;
515 }
516
517 bool
518 Path::setStatusInfo(const StatusInfo& si) const {
519   if (!isFile()) return false;
520   struct utimbuf utb;
521   utb.actime = si.modTime.toPosixTime();
522   utb.modtime = utb.actime;
523   if (0 != ::utime(path.c_str(),&utb))
524     ThrowErrno(path + ": can't set file modification time");
525   if (0 != ::chmod(path.c_str(),si.mode))
526     ThrowErrno(path + ": can't set mode");
527   return true;
528 }
529
530 }
531
532 // vim: sw=2