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