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