blob: 025357258dc76768b9e5475070a53c0866352938 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- 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#if HAVE_SYS_STAT_H
22#include <sys/stat.h>
23#endif
24#if HAVE_FCNTL_H
25#include <fcntl.h>
26#endif
27#if HAVE_UTIME_H
28#include <utime.h>
29#endif
30#if HAVE_TIME_H
31#include <time.h>
32#endif
33#if HAVE_DIRENT_H
34# include <dirent.h>
35# define NAMLEN(dirent) strlen((dirent)->d_name)
36#else
37# define dirent direct
38# define NAMLEN(dirent) (dirent)->d_namlen
39# if HAVE_SYS_NDIR_H
40# include <sys/ndir.h>
41# endif
42# if HAVE_SYS_DIR_H
43# include <sys/dir.h>
44# endif
45# if HAVE_NDIR_H
46# include <ndir.h>
47# endif
48#endif
49
50// Put in a hack for Cygwin which falsely reports that the mkdtemp function
51// is available when it is not.
52#ifdef __CYGWIN__
53# undef HAVE_MKDTEMP
54#endif
55
56namespace {
57inline bool lastIsSlash(const std::string& path) {
58 return !path.empty() && path[path.length() - 1] == '/';
59}
60
61}
62
63namespace llvm {
64using namespace sys;
65
66bool
67Path::isValid() const {
68 // Check some obvious things
69 if (path.empty())
70 return false;
71 else if (path.length() >= MAXPATHLEN)
72 return false;
73
74 // Check that the characters are ascii chars
75 size_t len = path.length();
76 unsigned i = 0;
77 while (i < len && isascii(path[i]))
78 ++i;
79 return i >= len;
80}
81
82bool
83Path::isAbsolute() const {
84 if (path.empty())
85 return false;
86 return path[0] == '/';
87}
88Path
89Path::GetRootDirectory() {
90 Path result;
91 result.set("/");
92 return result;
93}
94
95Path
96Path::GetTemporaryDirectory(std::string* ErrMsg ) {
97#if defined(HAVE_MKDTEMP)
98 // The best way is with mkdtemp but that's not available on many systems,
99 // Linux and FreeBSD have it. Others probably won't.
100 char pathname[MAXPATHLEN];
101 strcpy(pathname,"/tmp/llvm_XXXXXX");
102 if (0 == mkdtemp(pathname)) {
103 MakeErrMsg(ErrMsg,
104 std::string(pathname) + ": can't create temporary directory");
105 return Path();
106 }
107 Path result;
108 result.set(pathname);
109 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
110 return result;
111#elif defined(HAVE_MKSTEMP)
112 // If no mkdtemp is available, mkstemp can be used to create a temporary file
113 // which is then removed and created as a directory. We prefer this over
114 // mktemp because of mktemp's inherent security and threading risks. We still
115 // have a slight race condition from the time the temporary file is created to
116 // the time it is re-created as a directoy.
117 char pathname[MAXPATHLEN];
118 strcpy(pathname, "/tmp/llvm_XXXXXX");
119 int fd = 0;
120 if (-1 == (fd = mkstemp(pathname))) {
121 MakeErrMsg(ErrMsg,
122 std::string(pathname) + ": can't create temporary directory");
123 return Path();
124 }
125 ::close(fd);
126 ::unlink(pathname); // start race condition, ignore errors
127 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
128 MakeErrMsg(ErrMsg,
129 std::string(pathname) + ": can't create temporary directory");
130 return Path();
131 }
132 Path result;
133 result.set(pathname);
134 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
135 return result;
136#elif defined(HAVE_MKTEMP)
137 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
138 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
139 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
140 // the XXXXXX with the pid of the process and a letter. That leads to only
141 // twenty six temporary files that can be generated.
142 char pathname[MAXPATHLEN];
143 strcpy(pathname, "/tmp/llvm_XXXXXX");
144 char *TmpName = ::mktemp(pathname);
145 if (TmpName == 0) {
146 MakeErrMsg(ErrMsg,
147 std::string(TmpName) + ": can't create unique directory name");
148 return Path();
149 }
150 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
151 MakeErrMsg(ErrMsg,
152 std::string(TmpName) + ": can't create temporary directory");
153 return Path();
154 }
155 Path result;
156 result.set(TmpName);
157 assert(result.isValid() && "mktemp didn't create a valid pathname!");
158 return result;
159#else
160 // This is the worst case implementation. tempnam(3) leaks memory unless its
161 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
162 // issues. The mktemp(3) function doesn't have enough variability in the
163 // temporary name generated. So, we provide our own implementation that
164 // increments an integer from a random number seeded by the current time. This
165 // should be sufficiently unique that we don't have many collisions between
166 // processes. Generally LLVM processes don't run very long and don't use very
167 // many temporary files so this shouldn't be a big issue for LLVM.
168 static time_t num = ::time(0);
169 char pathname[MAXPATHLEN];
170 do {
171 num++;
172 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
173 } while ( 0 == access(pathname, F_OK ) );
174 if (-1 == ::mkdir(pathname, S_IRWXU)) {
175 MakeErrMsg(ErrMsg,
176 std::string(pathname) + ": can't create temporary directory");
177 return Path();
178 }
179 Path result;
180 result.set(pathname);
181 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
182 return result;
183#endif
184}
185
186static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
187 const char* at = path;
188 const char* delim = strchr(at, ':');
189 Path tmpPath;
190 while( delim != 0 ) {
191 std::string tmp(at, size_t(delim-at));
192 if (tmpPath.set(tmp))
193 if (tmpPath.canRead())
194 Paths.push_back(tmpPath);
195 at = delim + 1;
196 delim = strchr(at, ':');
197 }
198 if (*at != 0)
199 if (tmpPath.set(std::string(at)))
200 if (tmpPath.canRead())
201 Paths.push_back(tmpPath);
202
203}
204
205void
206Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
207#ifdef LTDL_SHLIBPATH_VAR
208 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
209 if (env_var != 0) {
210 getPathList(env_var,Paths);
211 }
212#endif
213 // FIXME: Should this look at LD_LIBRARY_PATH too?
214 Paths.push_back(sys::Path("/usr/local/lib/"));
215 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
216 Paths.push_back(sys::Path("/usr/lib/"));
217 Paths.push_back(sys::Path("/lib/"));
218}
219
220void
221Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
222 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
223 if (env_var != 0) {
224 getPathList(env_var,Paths);
225 }
226#ifdef LLVM_LIBDIR
227 {
228 Path tmpPath;
229 if (tmpPath.set(LLVM_LIBDIR))
230 if (tmpPath.canRead())
231 Paths.push_back(tmpPath);
232 }
233#endif
234 GetSystemLibraryPaths(Paths);
235}
236
237Path
238Path::GetLLVMDefaultConfigDir() {
239 return Path("/etc/llvm/");
240}
241
242Path
243Path::GetUserHomeDirectory() {
244 const char* home = getenv("HOME");
245 if (home) {
246 Path result;
247 if (result.set(home))
248 return result;
249 }
250 return GetRootDirectory();
251}
252
Ted Kremenekb05c9352007-12-18 22:07:33 +0000253Path
254Path::GetCurrentDirectory() {
255 char pathname[MAXPATHLEN];
256 if (!getcwd(pathname,MAXPATHLEN)) {
257 assert (false && "Could not query current working directory.");
258 return Path("");
259 }
260
261 return Path(pathname);
262}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263
264std::string
265Path::getBasename() const {
266 // Find the last slash
267 size_t slash = path.rfind('/');
268 if (slash == std::string::npos)
269 slash = 0;
270 else
271 slash++;
272
273 size_t dot = path.rfind('.');
274 if (dot == std::string::npos || dot < slash)
275 return path.substr(slash);
276 else
277 return path.substr(slash, dot - slash);
278}
279
280bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
281 assert(len < 1024 && "Request for magic string too long");
282 char* buf = (char*) alloca(1 + len);
283 int fd = ::open(path.c_str(), O_RDONLY);
284 if (fd < 0)
285 return false;
286 ssize_t bytes_read = ::read(fd, buf, len);
287 ::close(fd);
288 if (ssize_t(len) != bytes_read) {
289 Magic.clear();
290 return false;
291 }
292 Magic.assign(buf,len);
293 return true;
294}
295
296bool
297Path::exists() const {
298 return 0 == access(path.c_str(), F_OK );
299}
300
301bool
Ted Kremenek65149be2007-12-18 19:46:22 +0000302Path::isDirectory() const {
303 struct stat buf;
304 if (0 != stat(path.c_str(), &buf))
305 return false;
306 return buf.st_mode & S_IFDIR ? true : false;
307}
308
309bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000310Path::canRead() const {
311 return 0 == access(path.c_str(), F_OK | R_OK );
312}
313
314bool
315Path::canWrite() const {
316 return 0 == access(path.c_str(), F_OK | W_OK );
317}
318
319bool
320Path::canExecute() const {
321 if (0 != access(path.c_str(), R_OK | X_OK ))
322 return false;
323 struct stat buf;
324 if (0 != stat(path.c_str(), &buf))
325 return false;
326 if (!S_ISREG(buf.st_mode))
327 return false;
328 return true;
329}
330
331std::string
332Path::getLast() const {
333 // Find the last slash
334 size_t pos = path.rfind('/');
335
336 // Handle the corner cases
337 if (pos == std::string::npos)
338 return path;
339
340 // If the last character is a slash
341 if (pos == path.length()-1) {
342 // Find the second to last slash
343 size_t pos2 = path.rfind('/', pos-1);
344 if (pos2 == std::string::npos)
345 return path.substr(0,pos);
346 else
347 return path.substr(pos2+1,pos-pos2-1);
348 }
349 // Return everything after the last slash
350 return path.substr(pos+1);
351}
352
353const FileStatus *
354PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
355 if (!fsIsValid || update) {
356 struct stat buf;
357 if (0 != stat(path.c_str(), &buf)) {
358 MakeErrMsg(ErrStr, path + ": can't get status of file");
359 return 0;
360 }
361 status.fileSize = buf.st_size;
362 status.modTime.fromEpochTime(buf.st_mtime);
363 status.mode = buf.st_mode;
364 status.user = buf.st_uid;
365 status.group = buf.st_gid;
366 status.uniqueID = uint64_t(buf.st_ino);
367 status.isDir = S_ISDIR(buf.st_mode);
368 status.isFile = S_ISREG(buf.st_mode);
369 fsIsValid = true;
370 }
371 return &status;
372}
373
374static bool AddPermissionBits(const Path &File, int bits) {
375 // Get the umask value from the operating system. We want to use it
376 // when changing the file's permissions. Since calling umask() sets
377 // the umask and returns its old value, we must call it a second
378 // time to reset it to the user's preference.
379 int mask = umask(0777); // The arg. to umask is arbitrary.
380 umask(mask); // Restore the umask.
381
382 // Get the file's current mode.
383 struct stat buf;
384 if (0 != stat(File.toString().c_str(), &buf))
385 return false;
386 // Change the file to have whichever permissions bits from 'bits'
387 // that the umask would not disable.
388 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
389 return false;
390 return true;
391}
392
393bool Path::makeReadableOnDisk(std::string* ErrMsg) {
394 if (!AddPermissionBits(*this, 0444))
395 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
396 return false;
397}
398
399bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
400 if (!AddPermissionBits(*this, 0222))
401 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
402 return false;
403}
404
405bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
406 if (!AddPermissionBits(*this, 0111))
407 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
408 return false;
409}
410
411bool
412Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
413 DIR* direntries = ::opendir(path.c_str());
414 if (direntries == 0)
415 return MakeErrMsg(ErrMsg, path + ": can't open directory");
416
417 std::string dirPath = path;
418 if (!lastIsSlash(dirPath))
419 dirPath += '/';
420
421 result.clear();
422 struct dirent* de = ::readdir(direntries);
423 for ( ; de != 0; de = ::readdir(direntries)) {
424 if (de->d_name[0] != '.') {
425 Path aPath(dirPath + (const char*)de->d_name);
426 struct stat st;
427 if (0 != lstat(aPath.path.c_str(), &st)) {
428 if (S_ISLNK(st.st_mode))
429 continue; // dangling symlink -- ignore
430 return MakeErrMsg(ErrMsg,
431 aPath.path + ": can't determine file object type");
432 }
433 result.insert(aPath);
434 }
435 }
436
437 closedir(direntries);
438 return false;
439}
440
441bool
442Path::set(const std::string& a_path) {
443 if (a_path.empty())
444 return false;
445 std::string save(path);
446 path = a_path;
447 if (!isValid()) {
448 path = save;
449 return false;
450 }
451 return true;
452}
453
454bool
455Path::appendComponent(const std::string& name) {
456 if (name.empty())
457 return false;
458 std::string save(path);
459 if (!lastIsSlash(path))
460 path += '/';
461 path += name;
462 if (!isValid()) {
463 path = save;
464 return false;
465 }
466 return true;
467}
468
469bool
470Path::eraseComponent() {
471 size_t slashpos = path.rfind('/',path.size());
472 if (slashpos == 0 || slashpos == std::string::npos) {
473 path.erase();
474 return true;
475 }
476 if (slashpos == path.size() - 1)
477 slashpos = path.rfind('/',slashpos-1);
478 if (slashpos == std::string::npos) {
479 path.erase();
480 return true;
481 }
482 path.erase(slashpos);
483 return true;
484}
485
486bool
487Path::appendSuffix(const std::string& suffix) {
488 std::string save(path);
489 path.append(".");
490 path.append(suffix);
491 if (!isValid()) {
492 path = save;
493 return false;
494 }
495 return true;
496}
497
498bool
499Path::eraseSuffix() {
500 std::string save = path;
501 size_t dotpos = path.rfind('.',path.size());
502 size_t slashpos = path.rfind('/',path.size());
503 if (dotpos != std::string::npos) {
504 if (slashpos == std::string::npos || dotpos > slashpos+1) {
505 path.erase(dotpos, path.size()-dotpos);
506 return true;
507 }
508 }
509 if (!isValid())
510 path = save;
511 return false;
512}
513
514bool
515Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
516 // Get a writeable copy of the path name
517 char pathname[MAXPATHLEN];
518 path.copy(pathname,MAXPATHLEN);
519
520 // Null-terminate the last component
521 int lastchar = path.length() - 1 ;
522 if (pathname[lastchar] == '/')
523 pathname[lastchar] = 0;
524 else
525 pathname[lastchar+1] = 0;
526
527 // If we're supposed to create intermediate directories
528 if ( create_parents ) {
529 // Find the end of the initial name component
530 char * next = strchr(pathname,'/');
531 if ( pathname[0] == '/')
532 next = strchr(&pathname[1],'/');
533
534 // Loop through the directory components until we're done
535 while ( next != 0 ) {
536 *next = 0;
537 if (0 != access(pathname, F_OK | R_OK | W_OK))
538 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
539 return MakeErrMsg(ErrMsg,
540 std::string(pathname) + ": can't create directory");
541 }
542 char* save = next;
543 next = strchr(next+1,'/');
544 *save = '/';
545 }
546 }
547
548 if (0 != access(pathname, F_OK | R_OK))
549 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
550 return MakeErrMsg(ErrMsg,
551 std::string(pathname) + ": can't create directory");
552 }
553 return false;
554}
555
556bool
557Path::createFileOnDisk(std::string* ErrMsg) {
558 // Create the file
559 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
560 if (fd < 0)
561 return MakeErrMsg(ErrMsg, path + ": can't create file");
562 ::close(fd);
563 return false;
564}
565
566bool
567Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
568 // Make this into a unique file name
569 if (makeUnique( reuse_current, ErrMsg ))
570 return true;
571
572 // create the file
573 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
574 if (fd < 0)
575 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
576 ::close(fd);
577 return false;
578}
579
580bool
581Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
582 // Get the status so we can determin if its a file or directory
583 struct stat buf;
584 if (0 != stat(path.c_str(), &buf)) {
585 MakeErrMsg(ErrStr, path + ": can't get status of file");
586 return true;
587 }
588
589 // Note: this check catches strange situations. In all cases, LLVM should
590 // only be involved in the creation and deletion of regular files. This
591 // check ensures that what we're trying to erase is a regular file. It
592 // effectively prevents LLVM from erasing things like /dev/null, any block
593 // special file, or other things that aren't "regular" files.
594 if (S_ISREG(buf.st_mode)) {
595 if (unlink(path.c_str()) != 0)
596 return MakeErrMsg(ErrStr, path + ": can't destroy file");
597 return false;
598 }
599
600 if (!S_ISDIR(buf.st_mode)) {
601 if (ErrStr) *ErrStr = "not a file or directory";
602 return true;
603 }
604
605 if (remove_contents) {
606 // Recursively descend the directory to remove its contents.
607 std::string cmd = "/bin/rm -rf " + path;
608 system(cmd.c_str());
609 return false;
610 }
611
612 // Otherwise, try to just remove the one directory.
613 char pathname[MAXPATHLEN];
614 path.copy(pathname, MAXPATHLEN);
615 int lastchar = path.length() - 1 ;
616 if (pathname[lastchar] == '/')
617 pathname[lastchar] = 0;
618 else
619 pathname[lastchar+1] = 0;
620
621 if (rmdir(pathname) != 0)
622 return MakeErrMsg(ErrStr,
623 std::string(pathname) + ": can't erase directory");
624 return false;
625}
626
627bool
628Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
629 if (0 != ::rename(path.c_str(), newName.c_str()))
630 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
631 newName.toString() + "' ");
632 return false;
633}
634
635bool
636Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
637 struct utimbuf utb;
638 utb.actime = si.modTime.toPosixTime();
639 utb.modtime = utb.actime;
640 if (0 != ::utime(path.c_str(),&utb))
641 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
642 if (0 != ::chmod(path.c_str(),si.mode))
643 return MakeErrMsg(ErrStr, path + ": can't set mode");
644 return false;
645}
646
647bool
648sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
649 int inFile = -1;
650 int outFile = -1;
651 inFile = ::open(Src.c_str(), O_RDONLY);
652 if (inFile == -1)
653 return MakeErrMsg(ErrMsg, Src.toString() +
654 ": can't open source file to copy");
655
656 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
657 if (outFile == -1) {
658 ::close(inFile);
659 return MakeErrMsg(ErrMsg, Dest.toString() +
660 ": can't create destination file for copy");
661 }
662
663 char Buffer[16*1024];
664 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
665 if (Amt == -1) {
666 if (errno != EINTR && errno != EAGAIN) {
667 ::close(inFile);
668 ::close(outFile);
669 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file: ");
670 }
671 } else {
672 char *BufPtr = Buffer;
673 while (Amt) {
674 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
675 if (AmtWritten == -1) {
676 if (errno != EINTR && errno != EAGAIN) {
677 ::close(inFile);
678 ::close(outFile);
679 return MakeErrMsg(ErrMsg, Dest.toString() +
680 ": can't write destination file: ");
681 }
682 } else {
683 Amt -= AmtWritten;
684 BufPtr += AmtWritten;
685 }
686 }
687 }
688 }
689 ::close(inFile);
690 ::close(outFile);
691 return false;
692}
693
694bool
695Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
696 if (reuse_current && !exists())
697 return false; // File doesn't exist already, just use it!
698
699 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
700 // mktemp or our own implementation.
701 char *FNBuffer = (char*) alloca(path.size()+8);
702 path.copy(FNBuffer,path.size());
703 strcpy(FNBuffer+path.size(), "-XXXXXX");
704
705#if defined(HAVE_MKSTEMP)
706 int TempFD;
707 if ((TempFD = mkstemp(FNBuffer)) == -1)
708 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
709
710 // We don't need to hold the temp file descriptor... we will trust that no one
711 // will overwrite/delete the file before we can open it again.
712 close(TempFD);
713
714 // Save the name
715 path = FNBuffer;
716#elif defined(HAVE_MKTEMP)
717 // If we don't have mkstemp, use the old and obsolete mktemp function.
718 if (mktemp(FNBuffer) == 0)
719 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
720
721 // Save the name
722 path = FNBuffer;
723#else
724 // Okay, looks like we have to do it all by our lonesome.
725 static unsigned FCounter = 0;
726 unsigned offset = path.size() + 1;
727 while ( FCounter < 999999 && exists()) {
728 sprintf(FNBuffer+offset,"%06u",++FCounter);
729 path = FNBuffer;
730 }
731 if (FCounter > 999999)
732 return MakeErrMsg(ErrMsg,
733 path + ": can't make unique filename: too many files");
734#endif
735 return false;
736}
737
738} // end llvm namespace
739