blob: 9e90dda04e0522eaf579a45c4b7a6303d435a5aa [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
253
254std::string
255Path::getBasename() const {
256 // Find the last slash
257 size_t slash = path.rfind('/');
258 if (slash == std::string::npos)
259 slash = 0;
260 else
261 slash++;
262
263 size_t dot = path.rfind('.');
264 if (dot == std::string::npos || dot < slash)
265 return path.substr(slash);
266 else
267 return path.substr(slash, dot - slash);
268}
269
270bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
271 assert(len < 1024 && "Request for magic string too long");
272 char* buf = (char*) alloca(1 + len);
273 int fd = ::open(path.c_str(), O_RDONLY);
274 if (fd < 0)
275 return false;
276 ssize_t bytes_read = ::read(fd, buf, len);
277 ::close(fd);
278 if (ssize_t(len) != bytes_read) {
279 Magic.clear();
280 return false;
281 }
282 Magic.assign(buf,len);
283 return true;
284}
285
286bool
287Path::exists() const {
288 return 0 == access(path.c_str(), F_OK );
289}
290
291bool
Ted Kremenek65149be2007-12-18 19:46:22 +0000292Path::isDirectory() const {
293 struct stat buf;
294 if (0 != stat(path.c_str(), &buf))
295 return false;
296 return buf.st_mode & S_IFDIR ? true : false;
297}
298
299bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300Path::canRead() const {
301 return 0 == access(path.c_str(), F_OK | R_OK );
302}
303
304bool
305Path::canWrite() const {
306 return 0 == access(path.c_str(), F_OK | W_OK );
307}
308
309bool
310Path::canExecute() const {
311 if (0 != access(path.c_str(), R_OK | X_OK ))
312 return false;
313 struct stat buf;
314 if (0 != stat(path.c_str(), &buf))
315 return false;
316 if (!S_ISREG(buf.st_mode))
317 return false;
318 return true;
319}
320
321std::string
322Path::getLast() const {
323 // Find the last slash
324 size_t pos = path.rfind('/');
325
326 // Handle the corner cases
327 if (pos == std::string::npos)
328 return path;
329
330 // If the last character is a slash
331 if (pos == path.length()-1) {
332 // Find the second to last slash
333 size_t pos2 = path.rfind('/', pos-1);
334 if (pos2 == std::string::npos)
335 return path.substr(0,pos);
336 else
337 return path.substr(pos2+1,pos-pos2-1);
338 }
339 // Return everything after the last slash
340 return path.substr(pos+1);
341}
342
343const FileStatus *
344PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
345 if (!fsIsValid || update) {
346 struct stat buf;
347 if (0 != stat(path.c_str(), &buf)) {
348 MakeErrMsg(ErrStr, path + ": can't get status of file");
349 return 0;
350 }
351 status.fileSize = buf.st_size;
352 status.modTime.fromEpochTime(buf.st_mtime);
353 status.mode = buf.st_mode;
354 status.user = buf.st_uid;
355 status.group = buf.st_gid;
356 status.uniqueID = uint64_t(buf.st_ino);
357 status.isDir = S_ISDIR(buf.st_mode);
358 status.isFile = S_ISREG(buf.st_mode);
359 fsIsValid = true;
360 }
361 return &status;
362}
363
364static bool AddPermissionBits(const Path &File, int bits) {
365 // Get the umask value from the operating system. We want to use it
366 // when changing the file's permissions. Since calling umask() sets
367 // the umask and returns its old value, we must call it a second
368 // time to reset it to the user's preference.
369 int mask = umask(0777); // The arg. to umask is arbitrary.
370 umask(mask); // Restore the umask.
371
372 // Get the file's current mode.
373 struct stat buf;
374 if (0 != stat(File.toString().c_str(), &buf))
375 return false;
376 // Change the file to have whichever permissions bits from 'bits'
377 // that the umask would not disable.
378 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
379 return false;
380 return true;
381}
382
383bool Path::makeReadableOnDisk(std::string* ErrMsg) {
384 if (!AddPermissionBits(*this, 0444))
385 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
386 return false;
387}
388
389bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
390 if (!AddPermissionBits(*this, 0222))
391 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
392 return false;
393}
394
395bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
396 if (!AddPermissionBits(*this, 0111))
397 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
398 return false;
399}
400
401bool
402Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
403 DIR* direntries = ::opendir(path.c_str());
404 if (direntries == 0)
405 return MakeErrMsg(ErrMsg, path + ": can't open directory");
406
407 std::string dirPath = path;
408 if (!lastIsSlash(dirPath))
409 dirPath += '/';
410
411 result.clear();
412 struct dirent* de = ::readdir(direntries);
413 for ( ; de != 0; de = ::readdir(direntries)) {
414 if (de->d_name[0] != '.') {
415 Path aPath(dirPath + (const char*)de->d_name);
416 struct stat st;
417 if (0 != lstat(aPath.path.c_str(), &st)) {
418 if (S_ISLNK(st.st_mode))
419 continue; // dangling symlink -- ignore
420 return MakeErrMsg(ErrMsg,
421 aPath.path + ": can't determine file object type");
422 }
423 result.insert(aPath);
424 }
425 }
426
427 closedir(direntries);
428 return false;
429}
430
431bool
432Path::set(const std::string& a_path) {
433 if (a_path.empty())
434 return false;
435 std::string save(path);
436 path = a_path;
437 if (!isValid()) {
438 path = save;
439 return false;
440 }
441 return true;
442}
443
444bool
445Path::appendComponent(const std::string& name) {
446 if (name.empty())
447 return false;
448 std::string save(path);
449 if (!lastIsSlash(path))
450 path += '/';
451 path += name;
452 if (!isValid()) {
453 path = save;
454 return false;
455 }
456 return true;
457}
458
459bool
460Path::eraseComponent() {
461 size_t slashpos = path.rfind('/',path.size());
462 if (slashpos == 0 || slashpos == std::string::npos) {
463 path.erase();
464 return true;
465 }
466 if (slashpos == path.size() - 1)
467 slashpos = path.rfind('/',slashpos-1);
468 if (slashpos == std::string::npos) {
469 path.erase();
470 return true;
471 }
472 path.erase(slashpos);
473 return true;
474}
475
476bool
477Path::appendSuffix(const std::string& suffix) {
478 std::string save(path);
479 path.append(".");
480 path.append(suffix);
481 if (!isValid()) {
482 path = save;
483 return false;
484 }
485 return true;
486}
487
488bool
489Path::eraseSuffix() {
490 std::string save = path;
491 size_t dotpos = path.rfind('.',path.size());
492 size_t slashpos = path.rfind('/',path.size());
493 if (dotpos != std::string::npos) {
494 if (slashpos == std::string::npos || dotpos > slashpos+1) {
495 path.erase(dotpos, path.size()-dotpos);
496 return true;
497 }
498 }
499 if (!isValid())
500 path = save;
501 return false;
502}
503
504bool
505Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
506 // Get a writeable copy of the path name
507 char pathname[MAXPATHLEN];
508 path.copy(pathname,MAXPATHLEN);
509
510 // Null-terminate the last component
511 int lastchar = path.length() - 1 ;
512 if (pathname[lastchar] == '/')
513 pathname[lastchar] = 0;
514 else
515 pathname[lastchar+1] = 0;
516
517 // If we're supposed to create intermediate directories
518 if ( create_parents ) {
519 // Find the end of the initial name component
520 char * next = strchr(pathname,'/');
521 if ( pathname[0] == '/')
522 next = strchr(&pathname[1],'/');
523
524 // Loop through the directory components until we're done
525 while ( next != 0 ) {
526 *next = 0;
527 if (0 != access(pathname, F_OK | R_OK | W_OK))
528 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
529 return MakeErrMsg(ErrMsg,
530 std::string(pathname) + ": can't create directory");
531 }
532 char* save = next;
533 next = strchr(next+1,'/');
534 *save = '/';
535 }
536 }
537
538 if (0 != access(pathname, F_OK | R_OK))
539 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
540 return MakeErrMsg(ErrMsg,
541 std::string(pathname) + ": can't create directory");
542 }
543 return false;
544}
545
546bool
547Path::createFileOnDisk(std::string* ErrMsg) {
548 // Create the file
549 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
550 if (fd < 0)
551 return MakeErrMsg(ErrMsg, path + ": can't create file");
552 ::close(fd);
553 return false;
554}
555
556bool
557Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
558 // Make this into a unique file name
559 if (makeUnique( reuse_current, ErrMsg ))
560 return true;
561
562 // create the file
563 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
564 if (fd < 0)
565 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
566 ::close(fd);
567 return false;
568}
569
570bool
571Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
572 // Get the status so we can determin if its a file or directory
573 struct stat buf;
574 if (0 != stat(path.c_str(), &buf)) {
575 MakeErrMsg(ErrStr, path + ": can't get status of file");
576 return true;
577 }
578
579 // Note: this check catches strange situations. In all cases, LLVM should
580 // only be involved in the creation and deletion of regular files. This
581 // check ensures that what we're trying to erase is a regular file. It
582 // effectively prevents LLVM from erasing things like /dev/null, any block
583 // special file, or other things that aren't "regular" files.
584 if (S_ISREG(buf.st_mode)) {
585 if (unlink(path.c_str()) != 0)
586 return MakeErrMsg(ErrStr, path + ": can't destroy file");
587 return false;
588 }
589
590 if (!S_ISDIR(buf.st_mode)) {
591 if (ErrStr) *ErrStr = "not a file or directory";
592 return true;
593 }
594
595 if (remove_contents) {
596 // Recursively descend the directory to remove its contents.
597 std::string cmd = "/bin/rm -rf " + path;
598 system(cmd.c_str());
599 return false;
600 }
601
602 // Otherwise, try to just remove the one directory.
603 char pathname[MAXPATHLEN];
604 path.copy(pathname, MAXPATHLEN);
605 int lastchar = path.length() - 1 ;
606 if (pathname[lastchar] == '/')
607 pathname[lastchar] = 0;
608 else
609 pathname[lastchar+1] = 0;
610
611 if (rmdir(pathname) != 0)
612 return MakeErrMsg(ErrStr,
613 std::string(pathname) + ": can't erase directory");
614 return false;
615}
616
617bool
618Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
619 if (0 != ::rename(path.c_str(), newName.c_str()))
620 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
621 newName.toString() + "' ");
622 return false;
623}
624
625bool
626Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
627 struct utimbuf utb;
628 utb.actime = si.modTime.toPosixTime();
629 utb.modtime = utb.actime;
630 if (0 != ::utime(path.c_str(),&utb))
631 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
632 if (0 != ::chmod(path.c_str(),si.mode))
633 return MakeErrMsg(ErrStr, path + ": can't set mode");
634 return false;
635}
636
637bool
638sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
639 int inFile = -1;
640 int outFile = -1;
641 inFile = ::open(Src.c_str(), O_RDONLY);
642 if (inFile == -1)
643 return MakeErrMsg(ErrMsg, Src.toString() +
644 ": can't open source file to copy");
645
646 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
647 if (outFile == -1) {
648 ::close(inFile);
649 return MakeErrMsg(ErrMsg, Dest.toString() +
650 ": can't create destination file for copy");
651 }
652
653 char Buffer[16*1024];
654 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
655 if (Amt == -1) {
656 if (errno != EINTR && errno != EAGAIN) {
657 ::close(inFile);
658 ::close(outFile);
659 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file: ");
660 }
661 } else {
662 char *BufPtr = Buffer;
663 while (Amt) {
664 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
665 if (AmtWritten == -1) {
666 if (errno != EINTR && errno != EAGAIN) {
667 ::close(inFile);
668 ::close(outFile);
669 return MakeErrMsg(ErrMsg, Dest.toString() +
670 ": can't write destination file: ");
671 }
672 } else {
673 Amt -= AmtWritten;
674 BufPtr += AmtWritten;
675 }
676 }
677 }
678 }
679 ::close(inFile);
680 ::close(outFile);
681 return false;
682}
683
684bool
685Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
686 if (reuse_current && !exists())
687 return false; // File doesn't exist already, just use it!
688
689 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
690 // mktemp or our own implementation.
691 char *FNBuffer = (char*) alloca(path.size()+8);
692 path.copy(FNBuffer,path.size());
693 strcpy(FNBuffer+path.size(), "-XXXXXX");
694
695#if defined(HAVE_MKSTEMP)
696 int TempFD;
697 if ((TempFD = mkstemp(FNBuffer)) == -1)
698 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
699
700 // We don't need to hold the temp file descriptor... we will trust that no one
701 // will overwrite/delete the file before we can open it again.
702 close(TempFD);
703
704 // Save the name
705 path = FNBuffer;
706#elif defined(HAVE_MKTEMP)
707 // If we don't have mkstemp, use the old and obsolete mktemp function.
708 if (mktemp(FNBuffer) == 0)
709 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
710
711 // Save the name
712 path = FNBuffer;
713#else
714 // Okay, looks like we have to do it all by our lonesome.
715 static unsigned FCounter = 0;
716 unsigned offset = path.size() + 1;
717 while ( FCounter < 999999 && exists()) {
718 sprintf(FNBuffer+offset,"%06u",++FCounter);
719 path = FNBuffer;
720 }
721 if (FCounter > 999999)
722 return MakeErrMsg(ErrMsg,
723 path + ": can't make unique filename: too many files");
724#endif
725 return false;
726}
727
728} // end llvm namespace
729