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