Fix this for std::vectors which don't have .data().
[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 is distributed under the University of Illinois Open Source
6 // 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/ADT/SmallVector.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 #ifdef HAVE_SYS_MMAN_H
28 #include <sys/mman.h>
29 #endif
30 #ifdef HAVE_SYS_STAT_H
31 #include <sys/stat.h>
32 #endif
33 #if HAVE_UTIME_H
34 #include <utime.h>
35 #endif
36 #if HAVE_TIME_H
37 #include <time.h>
38 #endif
39 #if HAVE_DIRENT_H
40 # include <dirent.h>
41 # define NAMLEN(dirent) strlen((dirent)->d_name)
42 #else
43 # define dirent direct
44 # define NAMLEN(dirent) (dirent)->d_namlen
45 # if HAVE_SYS_NDIR_H
46 #  include <sys/ndir.h>
47 # endif
48 # if HAVE_SYS_DIR_H
49 #  include <sys/dir.h>
50 # endif
51 # if HAVE_NDIR_H
52 #  include <ndir.h>
53 # endif
54 #endif
55
56 #if HAVE_DLFCN_H
57 #include <dlfcn.h>
58 #endif
59
60 #ifdef __APPLE__
61 #include <mach-o/dyld.h>
62 #endif
63
64 // Put in a hack for Cygwin which falsely reports that the mkdtemp function
65 // is available when it is not.
66 #ifdef __CYGWIN__
67 # undef HAVE_MKDTEMP
68 #endif
69
70 namespace {
71 inline bool lastIsSlash(const std::string& path) {
72   return !path.empty() && path[path.length() - 1] == '/';
73 }
74
75 }
76
77 namespace llvm {
78 using namespace sys;
79
80 const char sys::PathSeparator = ':';
81
82 Path::Path(StringRef p)
83   : path(p) {}
84
85 Path::Path(const char *StrStart, unsigned StrLen)
86   : path(StrStart, StrLen) {}
87
88 Path&
89 Path::operator=(StringRef that) {
90   path.assign(that.data(), that.size());
91   return *this;
92 }
93
94 bool
95 Path::isValid() const {
96   // Check some obvious things
97   if (path.empty())
98     return false;
99   return path.length() < MAXPATHLEN;
100 }
101
102 bool
103 Path::isAbsolute(const char *NameStart, unsigned NameLen) {
104   assert(NameStart);
105   if (NameLen == 0)
106     return false;
107   return NameStart[0] == '/';
108 }
109
110 bool
111 Path::isAbsolute() const {
112   if (path.empty())
113     return false;
114   return path[0] == '/';
115 }
116
117 void Path::makeAbsolute() {
118   if (isAbsolute())
119     return;
120
121   Path CWD = Path::GetCurrentDirectory();
122   assert(CWD.isAbsolute() && "GetCurrentDirectory returned relative path!");
123
124   CWD.appendComponent(path);
125
126   path = CWD.str();
127 }
128
129 Path
130 Path::GetRootDirectory() {
131   Path result;
132   result.set("/");
133   return result;
134 }
135
136 Path
137 Path::GetTemporaryDirectory(std::string *ErrMsg) {
138 #if defined(HAVE_MKDTEMP)
139   // The best way is with mkdtemp but that's not available on many systems,
140   // Linux and FreeBSD have it. Others probably won't.
141   char pathname[MAXPATHLEN];
142   strcpy(pathname,"/tmp/llvm_XXXXXX");
143   if (0 == mkdtemp(pathname)) {
144     MakeErrMsg(ErrMsg,
145       std::string(pathname) + ": can't create temporary directory");
146     return Path();
147   }
148   Path result;
149   result.set(pathname);
150   assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
151   return result;
152 #elif defined(HAVE_MKSTEMP)
153   // If no mkdtemp is available, mkstemp can be used to create a temporary file
154   // which is then removed and created as a directory. We prefer this over
155   // mktemp because of mktemp's inherent security and threading risks. We still
156   // have a slight race condition from the time the temporary file is created to
157   // the time it is re-created as a directoy.
158   char pathname[MAXPATHLEN];
159   strcpy(pathname, "/tmp/llvm_XXXXXX");
160   int fd = 0;
161   if (-1 == (fd = mkstemp(pathname))) {
162     MakeErrMsg(ErrMsg,
163       std::string(pathname) + ": can't create temporary directory");
164     return Path();
165   }
166   ::close(fd);
167   ::unlink(pathname); // start race condition, ignore errors
168   if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
169     MakeErrMsg(ErrMsg,
170       std::string(pathname) + ": can't create temporary directory");
171     return Path();
172   }
173   Path result;
174   result.set(pathname);
175   assert(result.isValid() && "mkstemp didn't create a valid pathname!");
176   return result;
177 #elif defined(HAVE_MKTEMP)
178   // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
179   // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
180   // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
181   // the XXXXXX with the pid of the process and a letter. That leads to only
182   // twenty six temporary files that can be generated.
183   char pathname[MAXPATHLEN];
184   strcpy(pathname, "/tmp/llvm_XXXXXX");
185   char *TmpName = ::mktemp(pathname);
186   if (TmpName == 0) {
187     MakeErrMsg(ErrMsg,
188       std::string(TmpName) + ": can't create unique directory name");
189     return Path();
190   }
191   if (-1 == ::mkdir(TmpName, S_IRWXU)) {
192     MakeErrMsg(ErrMsg,
193         std::string(TmpName) + ": can't create temporary directory");
194     return Path();
195   }
196   Path result;
197   result.set(TmpName);
198   assert(result.isValid() && "mktemp didn't create a valid pathname!");
199   return result;
200 #else
201   // This is the worst case implementation. tempnam(3) leaks memory unless its
202   // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
203   // issues. The mktemp(3) function doesn't have enough variability in the
204   // temporary name generated. So, we provide our own implementation that
205   // increments an integer from a random number seeded by the current time. This
206   // should be sufficiently unique that we don't have many collisions between
207   // processes. Generally LLVM processes don't run very long and don't use very
208   // many temporary files so this shouldn't be a big issue for LLVM.
209   static time_t num = ::time(0);
210   char pathname[MAXPATHLEN];
211   do {
212     num++;
213     sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
214   } while ( 0 == access(pathname, F_OK ) );
215   if (-1 == ::mkdir(pathname, S_IRWXU)) {
216     MakeErrMsg(ErrMsg,
217       std::string(pathname) + ": can't create temporary directory");
218     return Path();
219   }
220   Path result;
221   result.set(pathname);
222   assert(result.isValid() && "mkstemp didn't create a valid pathname!");
223   return result;
224 #endif
225 }
226
227 void
228 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
229 #ifdef LTDL_SHLIBPATH_VAR
230   char* env_var = getenv(LTDL_SHLIBPATH_VAR);
231   if (env_var != 0) {
232     getPathList(env_var,Paths);
233   }
234 #endif
235   // FIXME: Should this look at LD_LIBRARY_PATH too?
236   Paths.push_back(sys::Path("/usr/local/lib/"));
237   Paths.push_back(sys::Path("/usr/X11R6/lib/"));
238   Paths.push_back(sys::Path("/usr/lib/"));
239   Paths.push_back(sys::Path("/lib/"));
240 }
241
242 void
243 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
244   char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
245   if (env_var != 0) {
246     getPathList(env_var,Paths);
247   }
248 #ifdef LLVM_LIBDIR
249   {
250     Path tmpPath;
251     if (tmpPath.set(LLVM_LIBDIR))
252       if (tmpPath.canRead())
253         Paths.push_back(tmpPath);
254   }
255 #endif
256   GetSystemLibraryPaths(Paths);
257 }
258
259 Path
260 Path::GetLLVMDefaultConfigDir() {
261   return Path("/etc/llvm/");
262 }
263
264 Path
265 Path::GetUserHomeDirectory() {
266   const char* home = getenv("HOME");
267   if (home) {
268     Path result;
269     if (result.set(home))
270       return result;
271   }
272   return GetRootDirectory();
273 }
274
275 Path
276 Path::GetCurrentDirectory() {
277   char pathname[MAXPATHLEN];
278   if (!getcwd(pathname,MAXPATHLEN)) {
279     assert (false && "Could not query current working directory.");
280     return Path("");
281   }
282
283   return Path(pathname);
284 }
285
286 #ifdef __FreeBSD__
287 static int
288 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
289     const char *dir, const char *bin)
290 {
291   struct stat sb;
292
293   snprintf(buf, PATH_MAX, "%s//%s", dir, bin);
294   if (realpath(buf, ret) == NULL)
295     return (1);
296   if (stat(buf, &sb) != 0)
297     return (1);
298
299   return (0);
300 }
301
302 static char *
303 getprogpath(char ret[PATH_MAX], const char *bin)
304 {
305   char *pv, *s, *t, buf[PATH_MAX];
306
307   /* First approach: absolute path. */
308   if (bin[0] == '/') {
309     if (test_dir(buf, ret, "/", bin) == 0)
310       return (ret);
311     return (NULL);
312   }
313
314   /* Second approach: relative path. */
315   if (strchr(bin, '/') != NULL) {
316     if (getcwd(buf, PATH_MAX) == NULL)
317       return (NULL);
318     if (test_dir(buf, ret, buf, bin) == 0)
319       return (ret);
320     return (NULL);
321   }
322
323   /* Third approach: $PATH */
324   if ((pv = getenv("PATH")) == NULL)
325     return (NULL);
326   s = pv = strdup(pv);
327   if (pv == NULL)
328     return (NULL);
329   while ((t = strsep(&s, ":")) != NULL) {
330     if (test_dir(buf, ret, t, bin) == 0) {
331       free(pv);
332       return (ret);
333     }
334   }
335   free(pv);
336   return (NULL);
337 }
338 #endif // __FreeBSD__
339
340 /// GetMainExecutable - Return the path to the main executable, given the
341 /// value of argv[0] from program startup.
342 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
343 #if defined(__APPLE__)
344   // On OS X the executable path is saved to the stack by dyld. Reading it
345   // from there is much faster than calling dladdr, especially for large
346   // binaries with symbols.
347   char exe_path[MAXPATHLEN];
348   uint32_t size = sizeof(exe_path);
349   if (_NSGetExecutablePath(exe_path, &size) == 0) {
350     char link_path[MAXPATHLEN];
351     if (realpath(exe_path, link_path))
352       return Path(std::string(link_path));
353   }
354 #elif defined(__FreeBSD__)
355   char exe_path[PATH_MAX];
356
357   if (getprogpath(exe_path, argv0) != NULL)
358     return Path(std::string(exe_path));
359 #elif defined(__linux__) || defined(__CYGWIN__)
360   char exe_path[MAXPATHLEN];
361   ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
362   if (len >= 0)
363     return Path(std::string(exe_path, len));
364 #elif defined(HAVE_DLFCN_H)
365   // Use dladdr to get executable path if available.
366   Dl_info DLInfo;
367   int err = dladdr(MainAddr, &DLInfo);
368   if (err == 0)
369     return Path();
370
371   // If the filename is a symlink, we need to resolve and return the location of
372   // the actual executable.
373   char link_path[MAXPATHLEN];
374   if (realpath(DLInfo.dli_fname, link_path))
375     return Path(std::string(link_path));
376 #endif
377   return Path();
378 }
379
380
381 StringRef Path::getDirname() const {
382   return getDirnameCharSep(path, "/");
383 }
384
385 StringRef
386 Path::getBasename() const {
387   // Find the last slash
388   std::string::size_type slash = path.rfind('/');
389   if (slash == std::string::npos)
390     slash = 0;
391   else
392     slash++;
393
394   std::string::size_type dot = path.rfind('.');
395   if (dot == std::string::npos || dot < slash)
396     return StringRef(path).substr(slash);
397   else
398     return StringRef(path).substr(slash, dot - slash);
399 }
400
401 StringRef
402 Path::getSuffix() const {
403   // Find the last slash
404   std::string::size_type slash = path.rfind('/');
405   if (slash == std::string::npos)
406     slash = 0;
407   else
408     slash++;
409
410   std::string::size_type dot = path.rfind('.');
411   if (dot == std::string::npos || dot < slash)
412     return StringRef("");
413   else
414     return StringRef(path).substr(dot + 1);
415 }
416
417 bool Path::getMagicNumber(std::string &Magic, unsigned len) const {
418   assert(len < 1024 && "Request for magic string too long");
419   char Buf[1025];
420   int fd = ::open(path.c_str(), O_RDONLY);
421   if (fd < 0)
422     return false;
423   ssize_t bytes_read = ::read(fd, Buf, len);
424   ::close(fd);
425   if (ssize_t(len) != bytes_read) {
426     Magic.clear();
427     return false;
428   }
429   Magic.assign(Buf, len);
430   return true;
431 }
432
433 bool
434 Path::exists() const {
435   return 0 == access(path.c_str(), F_OK );
436 }
437
438 bool
439 Path::isDirectory() const {
440   struct stat buf;
441   if (0 != stat(path.c_str(), &buf))
442     return false;
443   return buf.st_mode & S_IFDIR ? true : false;
444 }
445
446 bool
447 Path::canRead() const {
448   return 0 == access(path.c_str(), R_OK);
449 }
450
451 bool
452 Path::canWrite() const {
453   return 0 == access(path.c_str(), W_OK);
454 }
455
456 bool
457 Path::isRegularFile() const {
458   // Get the status so we can determine if it's a file or directory
459   struct stat buf;
460
461   if (0 != stat(path.c_str(), &buf))
462     return false;
463
464   if (S_ISREG(buf.st_mode))
465     return true;
466
467   return false;
468 }
469
470 bool
471 Path::canExecute() const {
472   if (0 != access(path.c_str(), R_OK | X_OK ))
473     return false;
474   struct stat buf;
475   if (0 != stat(path.c_str(), &buf))
476     return false;
477   if (!S_ISREG(buf.st_mode))
478     return false;
479   return true;
480 }
481
482 StringRef
483 Path::getLast() const {
484   // Find the last slash
485   size_t pos = path.rfind('/');
486
487   // Handle the corner cases
488   if (pos == std::string::npos)
489     return path;
490
491   // If the last character is a slash
492   if (pos == path.length()-1) {
493     // Find the second to last slash
494     size_t pos2 = path.rfind('/', pos-1);
495     if (pos2 == std::string::npos)
496       return StringRef(path).substr(0,pos);
497     else
498       return StringRef(path).substr(pos2+1,pos-pos2-1);
499   }
500   // Return everything after the last slash
501   return StringRef(path).substr(pos+1);
502 }
503
504 const FileStatus *
505 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
506   if (!fsIsValid || update) {
507     struct stat buf;
508     if (0 != stat(path.c_str(), &buf)) {
509       MakeErrMsg(ErrStr, path + ": can't get status of file");
510       return 0;
511     }
512     status.fileSize = buf.st_size;
513     status.modTime.fromEpochTime(buf.st_mtime);
514     status.mode = buf.st_mode;
515     status.user = buf.st_uid;
516     status.group = buf.st_gid;
517     status.uniqueID = uint64_t(buf.st_ino);
518     status.isDir  = S_ISDIR(buf.st_mode);
519     status.isFile = S_ISREG(buf.st_mode);
520     fsIsValid = true;
521   }
522   return &status;
523 }
524
525 static bool AddPermissionBits(const Path &File, int bits) {
526   // Get the umask value from the operating system.  We want to use it
527   // when changing the file's permissions. Since calling umask() sets
528   // the umask and returns its old value, we must call it a second
529   // time to reset it to the user's preference.
530   int mask = umask(0777); // The arg. to umask is arbitrary.
531   umask(mask);            // Restore the umask.
532
533   // Get the file's current mode.
534   struct stat buf;
535   if (0 != stat(File.c_str(), &buf))
536     return false;
537   // Change the file to have whichever permissions bits from 'bits'
538   // that the umask would not disable.
539   if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
540       return false;
541   return true;
542 }
543
544 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
545   if (!AddPermissionBits(*this, 0444))
546     return MakeErrMsg(ErrMsg, path + ": can't make file readable");
547   return false;
548 }
549
550 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
551   if (!AddPermissionBits(*this, 0222))
552     return MakeErrMsg(ErrMsg, path + ": can't make file writable");
553   return false;
554 }
555
556 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
557   if (!AddPermissionBits(*this, 0111))
558     return MakeErrMsg(ErrMsg, path + ": can't make file executable");
559   return false;
560 }
561
562 bool
563 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
564   DIR* direntries = ::opendir(path.c_str());
565   if (direntries == 0)
566     return MakeErrMsg(ErrMsg, path + ": can't open directory");
567
568   std::string dirPath = path;
569   if (!lastIsSlash(dirPath))
570     dirPath += '/';
571
572   result.clear();
573   struct dirent* de = ::readdir(direntries);
574   for ( ; de != 0; de = ::readdir(direntries)) {
575     if (de->d_name[0] != '.') {
576       Path aPath(dirPath + (const char*)de->d_name);
577       struct stat st;
578       if (0 != lstat(aPath.path.c_str(), &st)) {
579         if (S_ISLNK(st.st_mode))
580           continue; // dangling symlink -- ignore
581         return MakeErrMsg(ErrMsg,
582                           aPath.path +  ": can't determine file object type");
583       }
584       result.insert(aPath);
585     }
586   }
587
588   closedir(direntries);
589   return false;
590 }
591
592 bool
593 Path::set(StringRef a_path) {
594   if (a_path.empty())
595     return false;
596   std::string save(path);
597   path = a_path;
598   if (!isValid()) {
599     path = save;
600     return false;
601   }
602   return true;
603 }
604
605 bool
606 Path::appendComponent(StringRef name) {
607   if (name.empty())
608     return false;
609   std::string save(path);
610   if (!lastIsSlash(path))
611     path += '/';
612   path += name;
613   if (!isValid()) {
614     path = save;
615     return false;
616   }
617   return true;
618 }
619
620 bool
621 Path::eraseComponent() {
622   size_t slashpos = path.rfind('/',path.size());
623   if (slashpos == 0 || slashpos == std::string::npos) {
624     path.erase();
625     return true;
626   }
627   if (slashpos == path.size() - 1)
628     slashpos = path.rfind('/',slashpos-1);
629   if (slashpos == std::string::npos) {
630     path.erase();
631     return true;
632   }
633   path.erase(slashpos);
634   return true;
635 }
636
637 bool
638 Path::appendSuffix(StringRef suffix) {
639   std::string save(path);
640   path.append(".");
641   path.append(suffix);
642   if (!isValid()) {
643     path = save;
644     return false;
645   }
646   return true;
647 }
648
649 bool
650 Path::eraseSuffix() {
651   std::string save = path;
652   size_t dotpos = path.rfind('.',path.size());
653   size_t slashpos = path.rfind('/',path.size());
654   if (dotpos != std::string::npos) {
655     if (slashpos == std::string::npos || dotpos > slashpos+1) {
656       path.erase(dotpos, path.size()-dotpos);
657       return true;
658     }
659   }
660   if (!isValid())
661     path = save;
662   return false;
663 }
664
665 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
666
667   if (access(beg, R_OK | W_OK) == 0)
668     return false;
669
670   if (create_parents) {
671
672     char* c = end;
673
674     for (; c != beg; --c)
675       if (*c == '/') {
676
677         // Recurse to handling the parent directory.
678         *c = '\0';
679         bool x = createDirectoryHelper(beg, c, create_parents);
680         *c = '/';
681
682         // Return if we encountered an error.
683         if (x)
684           return true;
685
686         break;
687       }
688   }
689
690   return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
691 }
692
693 bool
694 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
695   // Get a writeable copy of the path name
696   char pathname[MAXPATHLEN];
697   path.copy(pathname,MAXPATHLEN);
698
699   // Null-terminate the last component
700   size_t lastchar = path.length() - 1 ;
701
702   if (pathname[lastchar] != '/')
703     ++lastchar;
704
705   pathname[lastchar] = 0;
706
707   if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
708     return MakeErrMsg(ErrMsg,
709                       std::string(pathname) + ": can't create directory");
710
711   return false;
712 }
713
714 bool
715 Path::createFileOnDisk(std::string* ErrMsg) {
716   // Create the file
717   int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
718   if (fd < 0)
719     return MakeErrMsg(ErrMsg, path + ": can't create file");
720   ::close(fd);
721   return false;
722 }
723
724 bool
725 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
726   // Make this into a unique file name
727   if (makeUnique( reuse_current, ErrMsg ))
728     return true;
729
730   // create the file
731   int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
732   if (fd < 0)
733     return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
734   ::close(fd);
735   return false;
736 }
737
738 bool
739 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
740   // Get the status so we can determine if it's a file or directory.
741   struct stat buf;
742   if (0 != stat(path.c_str(), &buf)) {
743     MakeErrMsg(ErrStr, path + ": can't get status of file");
744     return true;
745   }
746
747   // Note: this check catches strange situations. In all cases, LLVM should
748   // only be involved in the creation and deletion of regular files.  This
749   // check ensures that what we're trying to erase is a regular file. It
750   // effectively prevents LLVM from erasing things like /dev/null, any block
751   // special file, or other things that aren't "regular" files.
752   if (S_ISREG(buf.st_mode)) {
753     if (unlink(path.c_str()) != 0)
754       return MakeErrMsg(ErrStr, path + ": can't destroy file");
755     return false;
756   }
757
758   if (!S_ISDIR(buf.st_mode)) {
759     if (ErrStr) *ErrStr = "not a file or directory";
760     return true;
761   }
762
763   if (remove_contents) {
764     // Recursively descend the directory to remove its contents.
765     std::string cmd = "/bin/rm -rf " + path;
766     if (system(cmd.c_str()) != 0) {
767       MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
768       return true;
769     }
770     return false;
771   }
772
773   // Otherwise, try to just remove the one directory.
774   char pathname[MAXPATHLEN];
775   path.copy(pathname, MAXPATHLEN);
776   size_t lastchar = path.length() - 1;
777   if (pathname[lastchar] == '/')
778     pathname[lastchar] = 0;
779   else
780     pathname[lastchar+1] = 0;
781
782   if (rmdir(pathname) != 0)
783     return MakeErrMsg(ErrStr,
784       std::string(pathname) + ": can't erase directory");
785   return false;
786 }
787
788 bool
789 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
790   if (0 != ::rename(path.c_str(), newName.c_str()))
791     return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
792                newName.str() + "'");
793   return false;
794 }
795
796 bool
797 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
798   struct utimbuf utb;
799   utb.actime = si.modTime.toPosixTime();
800   utb.modtime = utb.actime;
801   if (0 != ::utime(path.c_str(),&utb))
802     return MakeErrMsg(ErrStr, path + ": can't set file modification time");
803   if (0 != ::chmod(path.c_str(),si.mode))
804     return MakeErrMsg(ErrStr, path + ": can't set mode");
805   return false;
806 }
807
808 bool
809 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
810   int inFile = -1;
811   int outFile = -1;
812   inFile = ::open(Src.c_str(), O_RDONLY);
813   if (inFile == -1)
814     return MakeErrMsg(ErrMsg, Src.str() +
815       ": can't open source file to copy");
816
817   outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
818   if (outFile == -1) {
819     ::close(inFile);
820     return MakeErrMsg(ErrMsg, Dest.str() +
821       ": can't create destination file for copy");
822   }
823
824   char Buffer[16*1024];
825   while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
826     if (Amt == -1) {
827       if (errno != EINTR && errno != EAGAIN) {
828         ::close(inFile);
829         ::close(outFile);
830         return MakeErrMsg(ErrMsg, Src.str()+": can't read source file");
831       }
832     } else {
833       char *BufPtr = Buffer;
834       while (Amt) {
835         ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
836         if (AmtWritten == -1) {
837           if (errno != EINTR && errno != EAGAIN) {
838             ::close(inFile);
839             ::close(outFile);
840             return MakeErrMsg(ErrMsg, Dest.str() +
841               ": can't write destination file");
842           }
843         } else {
844           Amt -= AmtWritten;
845           BufPtr += AmtWritten;
846         }
847       }
848     }
849   }
850   ::close(inFile);
851   ::close(outFile);
852   return false;
853 }
854
855 bool
856 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
857   if (reuse_current && !exists())
858     return false; // File doesn't exist already, just use it!
859
860   // Append an XXXXXX pattern to the end of the file for use with mkstemp,
861   // mktemp or our own implementation.
862   // This uses std::vector instead of SmallVector to avoid a dependence on
863   // libSupport. And performance isn't critical here.
864   std::vector<char> Buf;
865   Buf.resize(path.size()+8);
866   char *FNBuffer = &Buf[0];
867     path.copy(FNBuffer,path.size());
868   if (isDirectory())
869     strcpy(FNBuffer+path.size(), "/XXXXXX");
870   else
871     strcpy(FNBuffer+path.size(), "-XXXXXX");
872
873 #if defined(HAVE_MKSTEMP)
874   int TempFD;
875   if ((TempFD = mkstemp(FNBuffer)) == -1)
876     return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
877
878   // We don't need to hold the temp file descriptor... we will trust that no one
879   // will overwrite/delete the file before we can open it again.
880   close(TempFD);
881
882   // Save the name
883   path = FNBuffer;
884 #elif defined(HAVE_MKTEMP)
885   // If we don't have mkstemp, use the old and obsolete mktemp function.
886   if (mktemp(FNBuffer) == 0)
887     return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
888
889   // Save the name
890   path = FNBuffer;
891 #else
892   // Okay, looks like we have to do it all by our lonesome.
893   static unsigned FCounter = 0;
894   unsigned offset = path.size() + 1;
895   while ( FCounter < 999999 && exists()) {
896     sprintf(FNBuffer+offset,"%06u",++FCounter);
897     path = FNBuffer;
898   }
899   if (FCounter > 999999)
900     return MakeErrMsg(ErrMsg,
901       path + ": can't make unique filename: too many files");
902 #endif
903   return false;
904 }
905
906 const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
907   int Flags = MAP_PRIVATE;
908 #ifdef MAP_FILE
909   Flags |= MAP_FILE;
910 #endif
911   void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
912   if (BasePtr == MAP_FAILED)
913     return 0;
914   return (const char*)BasePtr;
915 }
916
917 void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
918   ::munmap((void*)BasePtr, FileSize);
919 }
920
921 } // end llvm namespace