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