Check that the 'kill' call succeeded.
[oota-llvm.git] / lib / System / Unix / Path.inc
1 //===- llvm/System/Unix/Path.cpp - Unix Path Implementation -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Unix specific portion of the Path class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic UNIX code that
16 //===          is guaranteed to work on *all* UNIX variants.
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/ADT/SmallVector.h"
20 #include "Unix.h"
21 #if HAVE_SYS_STAT_H
22 #include <sys/stat.h>
23 #endif
24 #if HAVE_FCNTL_H
25 #include <fcntl.h>
26 #endif
27 #ifdef HAVE_SYS_MMAN_H
28 #include <sys/mman.h>
29 #endif
30 #ifdef HAVE_SYS_STAT_H
31 #include <sys/stat.h>
32 #endif
33 #if HAVE_UTIME_H
34 #include <utime.h>
35 #endif
36 #if HAVE_TIME_H
37 #include <time.h>
38 #endif
39 #if HAVE_DIRENT_H
40 # include <dirent.h>
41 # define NAMLEN(dirent) strlen((dirent)->d_name)
42 #else
43 # define dirent direct
44 # define NAMLEN(dirent) (dirent)->d_namlen
45 # if HAVE_SYS_NDIR_H
46 #  include <sys/ndir.h>
47 # endif
48 # if HAVE_SYS_DIR_H
49 #  include <sys/dir.h>
50 # endif
51 # if HAVE_NDIR_H
52 #  include <ndir.h>
53 # endif
54 #endif
55
56 #if HAVE_DLFCN_H
57 #include <dlfcn.h>
58 #endif
59
60 // 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.str();
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   SmallVector<char, 128> Buf;
404   Buf.resize(1 + len);
405   char* buf = Buf.data();
406   int fd = ::open(path.c_str(), O_RDONLY);
407   if (fd < 0)
408     return false;
409   ssize_t bytes_read = ::read(fd, buf, len);
410   ::close(fd);
411   if (ssize_t(len) != bytes_read) {
412     Magic.clear();
413     return false;
414   }
415   Magic.assign(buf,len);
416   return true;
417 }
418
419 bool
420 Path::exists() const {
421   return 0 == access(path.c_str(), F_OK );
422 }
423
424 bool
425 Path::isDirectory() const {
426   struct stat buf;
427   if (0 != stat(path.c_str(), &buf))
428     return false;
429   return buf.st_mode & S_IFDIR ? true : false;
430 }
431
432 bool
433 Path::canRead() const {
434   return 0 == access(path.c_str(), R_OK);
435 }
436
437 bool
438 Path::canWrite() const {
439   return 0 == access(path.c_str(), W_OK);
440 }
441
442 bool
443 Path::canExecute() const {
444   if (0 != access(path.c_str(), R_OK | X_OK ))
445     return false;
446   struct stat buf;
447   if (0 != stat(path.c_str(), &buf))
448     return false;
449   if (!S_ISREG(buf.st_mode))
450     return false;
451   return true;
452 }
453
454 std::string
455 Path::getLast() const {
456   // Find the last slash
457   size_t pos = path.rfind('/');
458
459   // Handle the corner cases
460   if (pos == std::string::npos)
461     return path;
462
463   // If the last character is a slash
464   if (pos == path.length()-1) {
465     // Find the second to last slash
466     size_t pos2 = path.rfind('/', pos-1);
467     if (pos2 == std::string::npos)
468       return path.substr(0,pos);
469     else
470       return path.substr(pos2+1,pos-pos2-1);
471   }
472   // Return everything after the last slash
473   return path.substr(pos+1);
474 }
475
476 const FileStatus *
477 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
478   if (!fsIsValid || update) {
479     struct stat buf;
480     if (0 != stat(path.c_str(), &buf)) {
481       MakeErrMsg(ErrStr, path + ": can't get status of file");
482       return 0;
483     }
484     status.fileSize = buf.st_size;
485     status.modTime.fromEpochTime(buf.st_mtime);
486     status.mode = buf.st_mode;
487     status.user = buf.st_uid;
488     status.group = buf.st_gid;
489     status.uniqueID = uint64_t(buf.st_ino);
490     status.isDir  = S_ISDIR(buf.st_mode);
491     status.isFile = S_ISREG(buf.st_mode);
492     fsIsValid = true;
493   }
494   return &status;
495 }
496
497 static bool AddPermissionBits(const Path &File, int bits) {
498   // Get the umask value from the operating system.  We want to use it
499   // when changing the file's permissions. Since calling umask() sets
500   // the umask and returns its old value, we must call it a second
501   // time to reset it to the user's preference.
502   int mask = umask(0777); // The arg. to umask is arbitrary.
503   umask(mask);            // Restore the umask.
504
505   // Get the file's current mode.
506   struct stat buf;
507   if (0 != stat(File.c_str(), &buf))
508     return false;
509   // Change the file to have whichever permissions bits from 'bits'
510   // that the umask would not disable.
511   if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
512       return false;
513   return true;
514 }
515
516 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
517   if (!AddPermissionBits(*this, 0444))
518     return MakeErrMsg(ErrMsg, path + ": can't make file readable");
519   return false;
520 }
521
522 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
523   if (!AddPermissionBits(*this, 0222))
524     return MakeErrMsg(ErrMsg, path + ": can't make file writable");
525   return false;
526 }
527
528 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
529   if (!AddPermissionBits(*this, 0111))
530     return MakeErrMsg(ErrMsg, path + ": can't make file executable");
531   return false;
532 }
533
534 bool
535 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
536   DIR* direntries = ::opendir(path.c_str());
537   if (direntries == 0)
538     return MakeErrMsg(ErrMsg, path + ": can't open directory");
539
540   std::string dirPath = path;
541   if (!lastIsSlash(dirPath))
542     dirPath += '/';
543
544   result.clear();
545   struct dirent* de = ::readdir(direntries);
546   for ( ; de != 0; de = ::readdir(direntries)) {
547     if (de->d_name[0] != '.') {
548       Path aPath(dirPath + (const char*)de->d_name);
549       struct stat st;
550       if (0 != lstat(aPath.path.c_str(), &st)) {
551         if (S_ISLNK(st.st_mode))
552           continue; // dangling symlink -- ignore
553         return MakeErrMsg(ErrMsg,
554                           aPath.path +  ": can't determine file object type");
555       }
556       result.insert(aPath);
557     }
558   }
559
560   closedir(direntries);
561   return false;
562 }
563
564 bool
565 Path::set(const std::string& a_path) {
566   if (a_path.empty())
567     return false;
568   std::string save(path);
569   path = a_path;
570   if (!isValid()) {
571     path = save;
572     return false;
573   }
574   return true;
575 }
576
577 bool
578 Path::appendComponent(const std::string& name) {
579   if (name.empty())
580     return false;
581   std::string save(path);
582   if (!lastIsSlash(path))
583     path += '/';
584   path += name;
585   if (!isValid()) {
586     path = save;
587     return false;
588   }
589   return true;
590 }
591
592 bool
593 Path::eraseComponent() {
594   size_t slashpos = path.rfind('/',path.size());
595   if (slashpos == 0 || slashpos == std::string::npos) {
596     path.erase();
597     return true;
598   }
599   if (slashpos == path.size() - 1)
600     slashpos = path.rfind('/',slashpos-1);
601   if (slashpos == std::string::npos) {
602     path.erase();
603     return true;
604   }
605   path.erase(slashpos);
606   return true;
607 }
608
609 bool
610 Path::appendSuffix(const std::string& suffix) {
611   std::string save(path);
612   path.append(".");
613   path.append(suffix);
614   if (!isValid()) {
615     path = save;
616     return false;
617   }
618   return true;
619 }
620
621 bool
622 Path::eraseSuffix() {
623   std::string save = path;
624   size_t dotpos = path.rfind('.',path.size());
625   size_t slashpos = path.rfind('/',path.size());
626   if (dotpos != std::string::npos) {
627     if (slashpos == std::string::npos || dotpos > slashpos+1) {
628       path.erase(dotpos, path.size()-dotpos);
629       return true;
630     }
631   }
632   if (!isValid())
633     path = save;
634   return false;
635 }
636
637 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
638
639   if (access(beg, R_OK | W_OK) == 0)
640     return false;
641
642   if (create_parents) {
643
644     char* c = end;
645
646     for (; c != beg; --c)
647       if (*c == '/') {
648
649         // Recurse to handling the parent directory.
650         *c = '\0';
651         bool x = createDirectoryHelper(beg, c, create_parents);
652         *c = '/';
653
654         // Return if we encountered an error.
655         if (x)
656           return true;
657
658         break;
659       }
660   }
661
662   return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
663 }
664
665 bool
666 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
667   // Get a writeable copy of the path name
668   char pathname[MAXPATHLEN];
669   path.copy(pathname,MAXPATHLEN);
670
671   // Null-terminate the last component
672   size_t lastchar = path.length() - 1 ;
673
674   if (pathname[lastchar] != '/')
675     ++lastchar;
676
677   pathname[lastchar] = 0;
678
679   if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
680     return MakeErrMsg(ErrMsg,
681                       std::string(pathname) + ": can't create directory");
682
683   return false;
684 }
685
686 bool
687 Path::createFileOnDisk(std::string* ErrMsg) {
688   // Create the file
689   int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
690   if (fd < 0)
691     return MakeErrMsg(ErrMsg, path + ": can't create file");
692   ::close(fd);
693   return false;
694 }
695
696 bool
697 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
698   // Make this into a unique file name
699   if (makeUnique( reuse_current, ErrMsg ))
700     return true;
701
702   // create the file
703   int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
704   if (fd < 0)
705     return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
706   ::close(fd);
707   return false;
708 }
709
710 bool
711 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
712   // Get the status so we can determin if its a file or directory
713   struct stat buf;
714   if (0 != stat(path.c_str(), &buf)) {
715     MakeErrMsg(ErrStr, path + ": can't get status of file");
716     return true;
717   }
718
719   // Note: this check catches strange situations. In all cases, LLVM should
720   // only be involved in the creation and deletion of regular files.  This
721   // check ensures that what we're trying to erase is a regular file. It
722   // effectively prevents LLVM from erasing things like /dev/null, any block
723   // special file, or other things that aren't "regular" files.
724   if (S_ISREG(buf.st_mode)) {
725     if (unlink(path.c_str()) != 0)
726       return MakeErrMsg(ErrStr, path + ": can't destroy file");
727     return false;
728   }
729
730   if (!S_ISDIR(buf.st_mode)) {
731     if (ErrStr) *ErrStr = "not a file or directory";
732     return true;
733   }
734
735   if (remove_contents) {
736     // Recursively descend the directory to remove its contents.
737     std::string cmd = "/bin/rm -rf " + path;
738     if (system(cmd.c_str()) != 0) {
739       MakeErrMsg(ErrStr, path + ": failed to recursively remove directory.");
740       return true;
741     }
742     return false;
743   }
744
745   // Otherwise, try to just remove the one directory.
746   char pathname[MAXPATHLEN];
747   path.copy(pathname, MAXPATHLEN);
748   size_t lastchar = path.length() - 1;
749   if (pathname[lastchar] == '/')
750     pathname[lastchar] = 0;
751   else
752     pathname[lastchar+1] = 0;
753
754   if (rmdir(pathname) != 0)
755     return MakeErrMsg(ErrStr,
756       std::string(pathname) + ": can't erase directory");
757   return false;
758 }
759
760 bool
761 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
762   if (0 != ::rename(path.c_str(), newName.c_str()))
763     return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
764                newName.str() + "'");
765   return false;
766 }
767
768 bool
769 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
770   struct utimbuf utb;
771   utb.actime = si.modTime.toPosixTime();
772   utb.modtime = utb.actime;
773   if (0 != ::utime(path.c_str(),&utb))
774     return MakeErrMsg(ErrStr, path + ": can't set file modification time");
775   if (0 != ::chmod(path.c_str(),si.mode))
776     return MakeErrMsg(ErrStr, path + ": can't set mode");
777   return false;
778 }
779
780 bool
781 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
782   int inFile = -1;
783   int outFile = -1;
784   inFile = ::open(Src.c_str(), O_RDONLY);
785   if (inFile == -1)
786     return MakeErrMsg(ErrMsg, Src.str() +
787       ": can't open source file to copy");
788
789   outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
790   if (outFile == -1) {
791     ::close(inFile);
792     return MakeErrMsg(ErrMsg, Dest.str() +
793       ": can't create destination file for copy");
794   }
795
796   char Buffer[16*1024];
797   while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
798     if (Amt == -1) {
799       if (errno != EINTR && errno != EAGAIN) {
800         ::close(inFile);
801         ::close(outFile);
802         return MakeErrMsg(ErrMsg, Src.str()+": can't read source file");
803       }
804     } else {
805       char *BufPtr = Buffer;
806       while (Amt) {
807         ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
808         if (AmtWritten == -1) {
809           if (errno != EINTR && errno != EAGAIN) {
810             ::close(inFile);
811             ::close(outFile);
812             return MakeErrMsg(ErrMsg, Dest.str() +
813               ": can't write destination file");
814           }
815         } else {
816           Amt -= AmtWritten;
817           BufPtr += AmtWritten;
818         }
819       }
820     }
821   }
822   ::close(inFile);
823   ::close(outFile);
824   return false;
825 }
826
827 bool
828 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
829   if (reuse_current && !exists())
830     return false; // File doesn't exist already, just use it!
831
832   // Append an XXXXXX pattern to the end of the file for use with mkstemp,
833   // mktemp or our own implementation.
834   SmallVector<char, 128> Buf;
835   Buf.resize(path.size()+8);
836   char *FNBuffer = Buf.data();
837     path.copy(FNBuffer,path.size());
838   if (isDirectory())
839     strcpy(FNBuffer+path.size(), "/XXXXXX");
840   else
841     strcpy(FNBuffer+path.size(), "-XXXXXX");
842
843 #if defined(HAVE_MKSTEMP)
844   int TempFD;
845   if ((TempFD = mkstemp(FNBuffer)) == -1)
846     return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
847
848   // We don't need to hold the temp file descriptor... we will trust that no one
849   // will overwrite/delete the file before we can open it again.
850   close(TempFD);
851
852   // Save the name
853   path = FNBuffer;
854 #elif defined(HAVE_MKTEMP)
855   // If we don't have mkstemp, use the old and obsolete mktemp function.
856   if (mktemp(FNBuffer) == 0)
857     return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
858
859   // Save the name
860   path = FNBuffer;
861 #else
862   // Okay, looks like we have to do it all by our lonesome.
863   static unsigned FCounter = 0;
864   unsigned offset = path.size() + 1;
865   while ( FCounter < 999999 && exists()) {
866     sprintf(FNBuffer+offset,"%06u",++FCounter);
867     path = FNBuffer;
868   }
869   if (FCounter > 999999)
870     return MakeErrMsg(ErrMsg,
871       path + ": can't make unique filename: too many files");
872 #endif
873   return false;
874 }
875
876 const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
877   int Flags = MAP_PRIVATE;
878 #ifdef MAP_FILE
879   Flags |= MAP_FILE;
880 #endif
881   void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
882   if (BasePtr == MAP_FAILED)
883     return 0;
884   return (const char*)BasePtr;
885 }
886
887 void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
888   ::munmap((void*)BasePtr, FileSize);
889 }
890
891 } // end llvm namespace