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