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