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