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