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