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