Implement functionality suggested from code review: getStatusInfo should
[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 bool
243 Path::getStatusInfo(StatusInfo& info) {
244   if (!isFile() || !readable())
245     return false;
246   struct stat buf;
247   if (0 != stat(path.c_str(), &buf)) {
248     ThrowErrno(std::string("Can't get status: ")+path);
249   }
250   info.fileSize = buf.st_size;
251   info.modTime.fromEpochTime(buf.st_mtime);
252   info.mode = buf.st_mode;
253   info.user = buf.st_uid;
254   info.group = buf.st_gid;
255   info.isDir = S_ISDIR(buf.st_mode);
256   if (info.isDir && path[path.length()-1] != '/')
257     path += '/';
258   return true;
259 }
260
261 bool
262 Path::getDirectoryContents(Vector& result) const {
263   if (!isDirectory())
264     return false;
265   DIR* direntries = ::opendir(path.c_str());
266   if (direntries == 0)
267     ThrowErrno(path + ": can't open directory");
268
269   result.clear();
270   struct dirent* de = ::readdir(direntries);
271   while (de != 0) {
272     if (de->d_name[0] != '.') {
273       Path aPath(path + (const char*)de->d_name);
274       struct stat buf;
275       if (0 != stat(aPath.path.c_str(), &buf))
276         ThrowErrno(aPath.path + ": can't get status");
277       if (S_ISDIR(buf.st_mode))
278         aPath.path += "/";
279       result.push_back(aPath);
280     }
281     de = ::readdir(direntries);
282   }
283   
284   closedir(direntries);
285   return true;
286 }
287
288 bool
289 Path::setDirectory(const std::string& a_path) {
290   if (a_path.size() == 0)
291     return false;
292   Path save(*this);
293   path = a_path;
294   size_t last = a_path.size() -1;
295   if (last != 0 && a_path[last] != '/')
296     path += '/';
297   if (!isValid()) {
298     path = save.path;
299     return false;
300   }
301   return true;
302 }
303
304 bool
305 Path::setFile(const std::string& a_path) {
306   if (a_path.size() == 0)
307     return false;
308   Path save(*this);
309   path = a_path;
310   size_t last = a_path.size() - 1;
311   while (last > 0 && a_path[last] == '/')
312     last--;
313   path.erase(last+1);
314   if (!isValid()) {
315     path = save.path;
316     return false;
317   }
318   return true;
319 }
320
321 bool
322 Path::appendDirectory(const std::string& dir) {
323   if (isFile()) 
324     return false;
325   Path save(*this);
326   path += dir;
327   path += "/";
328   if (!isValid()) {
329     path = save.path;
330     return false;
331   }
332   return true;
333 }
334
335 bool
336 Path::elideDirectory() {
337   if (isFile()) 
338     return false;
339   size_t slashpos = path.rfind('/',path.size());
340   if (slashpos == 0 || slashpos == std::string::npos)
341     return false;
342   if (slashpos == path.size() - 1)
343     slashpos = path.rfind('/',slashpos-1);
344   if (slashpos == std::string::npos)
345     return false;
346   path.erase(slashpos);
347   return true;
348 }
349
350 bool
351 Path::appendFile(const std::string& file) {
352   if (!isDirectory()) 
353     return false;
354   Path save(*this);
355   path += file;
356   if (!isValid()) {
357     path = save.path;
358     return false;
359   }
360   return true;
361 }
362
363 bool
364 Path::elideFile() {
365   if (isDirectory()) 
366     return false;
367   size_t slashpos = path.rfind('/',path.size());
368   if (slashpos == std::string::npos)
369     return false;
370   path.erase(slashpos+1);
371   return true;
372 }
373
374 bool
375 Path::appendSuffix(const std::string& suffix) {
376   if (isDirectory()) 
377     return false;
378   Path save(*this);
379   path.append(".");
380   path.append(suffix);
381   if (!isValid()) {
382     path = save.path;
383     return false;
384   }
385   return true;
386 }
387
388 bool 
389 Path::elideSuffix() {
390   if (isDirectory()) return false;
391   size_t dotpos = path.rfind('.',path.size());
392   size_t slashpos = path.rfind('/',path.size());
393   if (slashpos != std::string::npos && dotpos != std::string::npos &&
394       dotpos > slashpos) {
395     path.erase(dotpos, path.size()-dotpos);
396     return true;
397   }
398   return false;
399 }
400
401
402 bool
403 Path::createDirectory( bool create_parents) {
404   // Make sure we're dealing with a directory
405   if (!isDirectory()) return false;
406
407   // Get a writeable copy of the path name
408   char pathname[MAXPATHLEN];
409   path.copy(pathname,MAXPATHLEN);
410
411   // Null-terminate the last component
412   int lastchar = path.length() - 1 ; 
413   if (pathname[lastchar] == '/') 
414     pathname[lastchar] = 0;
415   else 
416     pathname[lastchar+1] = 0;
417
418   // If we're supposed to create intermediate directories
419   if ( create_parents ) {
420     // Find the end of the initial name component
421     char * next = strchr(pathname,'/');
422     if ( pathname[0] == '/') 
423       next = strchr(&pathname[1],'/');
424
425     // Loop through the directory components until we're done 
426     while ( next != 0 ) {
427       *next = 0;
428       if (0 != access(pathname, F_OK | R_OK | W_OK))
429         if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
430           ThrowErrno(std::string(pathname) + ": Can't create directory");
431       char* save = next;
432       next = strchr(next+1,'/');
433       *save = '/';
434     }
435   } 
436
437   if (0 != access(pathname, F_OK | R_OK))
438     if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
439       ThrowErrno(std::string(pathname) + ": Can't create directory");
440   return true;
441 }
442
443 bool
444 Path::createFile() {
445   // Make sure we're dealing with a file
446   if (!isFile()) return false; 
447
448   // Create the file
449   int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
450   if (fd < 0)
451     ThrowErrno(path + ": Can't create file");
452   ::close(fd);
453
454   return true;
455 }
456
457 bool
458 Path::createTemporaryFile() {
459   // Make sure we're dealing with a file
460   if (!isFile()) return false;
461
462   // Append the filename filler
463   char pathname[MAXPATHLEN];
464   path.copy(pathname,MAXPATHLEN);
465   pathname[path.length()] = 0;
466   strcat(pathname,"XXXXXX");
467   int fd = ::mkstemp(pathname);
468   if (fd < 0) {
469     ThrowErrno(path + ": Can't create temporary file");
470   }
471   path = pathname;
472   ::close(fd);
473   return true;
474 }
475
476 bool
477 Path::destroyDirectory(bool remove_contents) {
478   // Make sure we're dealing with a directory
479   if (!isDirectory()) return false;
480
481   // If it doesn't exist, we're done.
482   if (!exists()) return true;
483
484   if (remove_contents) {
485     // Recursively descend the directory to remove its content
486     std::string cmd("/bin/rm -rf ");
487     cmd += path;
488     system(cmd.c_str());
489   } else {
490     // Otherwise, try to just remove the one directory
491     char pathname[MAXPATHLEN];
492     path.copy(pathname,MAXPATHLEN);
493     int lastchar = path.length() - 1 ; 
494     if (pathname[lastchar] == '/') 
495       pathname[lastchar] = 0;
496     else
497       pathname[lastchar+1] = 0;
498     if ( 0 != rmdir(pathname))
499       ThrowErrno(std::string(pathname) + ": Can't destroy directory");
500   }
501   return true;
502 }
503
504 bool
505 Path::destroyFile() {
506   if (!isFile()) return false;
507   if (0 != unlink(path.c_str()))
508     ThrowErrno(path + ": Can't destroy file");
509   return true;
510 }
511
512 bool
513 Path::renameFile(const Path& newName) {
514   if (!isFile()) return false;
515   if (0 != rename(path.c_str(), newName.c_str()))
516     ThrowErrno(std::string("can't rename ") + path + " as " + newName.get());
517   return true;
518 }
519
520 bool
521 Path::setStatusInfo(const StatusInfo& si) const {
522   if (!isFile()) return false;
523   struct utimbuf utb;
524   utb.actime = si.modTime.toPosixTime();
525   utb.modtime = utb.actime;
526   if (0 != ::utime(path.c_str(),&utb))
527     ThrowErrno(path + ": can't set file modification time");
528   if (0 != ::chmod(path.c_str(),si.mode))
529     ThrowErrno(path + ": can't set mode");
530   return true;
531 }
532
533 }
534
535 // vim: sw=2