5ee3adc4d2d4441ff58a26396cb847a520dc286d
[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 "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 void Path::makeAbsolute() {
123   if (isAbsolute())
124     return;
125
126   Path CWD = Path::GetCurrentDirectory();
127   assert(CWD.isAbsolute() && "GetCurrentDirectory returned relative path!");
128
129   CWD.appendComponent(path);
130
131   path = CWD.str();
132 }
133
134 Path
135 Path::GetRootDirectory() {
136   Path result;
137   result.set("/");
138   return result;
139 }
140
141 Path
142 Path::GetTemporaryDirectory(std::string *ErrMsg) {
143 #if defined(HAVE_MKDTEMP)
144   // The best way is with mkdtemp but that's not available on many systems,
145   // Linux and FreeBSD have it. Others probably won't.
146   char pathname[] = "/tmp/llvm_XXXXXX";
147   if (0 == mkdtemp(pathname)) {
148     MakeErrMsg(ErrMsg,
149                std::string(pathname) + ": can't create temporary directory");
150     return Path();
151   }
152   return Path(pathname);
153 #elif defined(HAVE_MKSTEMP)
154   // If no mkdtemp is available, mkstemp can be used to create a temporary file
155   // which is then removed and created as a directory. We prefer this over
156   // mktemp because of mktemp's inherent security and threading risks. We still
157   // have a slight race condition from the time the temporary file is created to
158   // the time it is re-created as a directoy.
159   char pathname[] = "/tmp/llvm_XXXXXX";
160   int fd = 0;
161   if (-1 == (fd = mkstemp(pathname))) {
162     MakeErrMsg(ErrMsg,
163       std::string(pathname) + ": can't create temporary directory");
164     return Path();
165   }
166   ::close(fd);
167   ::unlink(pathname); // start race condition, ignore errors
168   if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
169     MakeErrMsg(ErrMsg,
170       std::string(pathname) + ": can't create temporary directory");
171     return Path();
172   }
173   return Path(pathname);
174 #elif defined(HAVE_MKTEMP)
175   // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
176   // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
177   // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
178   // the XXXXXX with the pid of the process and a letter. That leads to only
179   // twenty six temporary files that can be generated.
180   char 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   return Path(TmpName);
193 #else
194   // This is the worst case implementation. tempnam(3) leaks memory unless its
195   // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
196   // issues. The mktemp(3) function doesn't have enough variability in the
197   // temporary name generated. So, we provide our own implementation that
198   // increments an integer from a random number seeded by the current time. This
199   // should be sufficiently unique that we don't have many collisions between
200   // processes. Generally LLVM processes don't run very long and don't use very
201   // many temporary files so this shouldn't be a big issue for LLVM.
202   static time_t num = ::time(0);
203   char pathname[MAXPATHLEN];
204   do {
205     num++;
206     sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
207   } while ( 0 == access(pathname, F_OK ) );
208   if (-1 == ::mkdir(pathname, S_IRWXU)) {
209     MakeErrMsg(ErrMsg,
210       std::string(pathname) + ": can't create temporary directory");
211     return Path();
212   }
213   return Path(pathname);
214 #endif
215 }
216
217 void
218 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
219 #ifdef LTDL_SHLIBPATH_VAR
220   char* env_var = getenv(LTDL_SHLIBPATH_VAR);
221   if (env_var != 0) {
222     getPathList(env_var,Paths);
223   }
224 #endif
225   // FIXME: Should this look at LD_LIBRARY_PATH too?
226   Paths.push_back(sys::Path("/usr/local/lib/"));
227   Paths.push_back(sys::Path("/usr/X11R6/lib/"));
228   Paths.push_back(sys::Path("/usr/lib/"));
229   Paths.push_back(sys::Path("/lib/"));
230 }
231
232 void
233 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
234   char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
235   if (env_var != 0) {
236     getPathList(env_var,Paths);
237   }
238 #ifdef LLVM_LIBDIR
239   {
240     Path tmpPath;
241     if (tmpPath.set(LLVM_LIBDIR))
242       if (tmpPath.canRead())
243         Paths.push_back(tmpPath);
244   }
245 #endif
246   GetSystemLibraryPaths(Paths);
247 }
248
249 Path
250 Path::GetLLVMDefaultConfigDir() {
251   return Path("/etc/llvm/");
252 }
253
254 Path
255 Path::GetUserHomeDirectory() {
256   const char* home = getenv("HOME");
257   if (home) {
258     Path result;
259     if (result.set(home))
260       return result;
261   }
262   return GetRootDirectory();
263 }
264
265 Path
266 Path::GetCurrentDirectory() {
267   char pathname[MAXPATHLEN];
268   if (!getcwd(pathname,MAXPATHLEN)) {
269     assert (false && "Could not query current working directory.");
270     return Path();
271   }
272
273   return Path(pathname);
274 }
275
276 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__minix)
277 static int
278 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
279     const char *dir, const char *bin)
280 {
281   struct stat sb;
282
283   snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
284   if (realpath(buf, ret) == NULL)
285     return (1);
286   if (stat(buf, &sb) != 0)
287     return (1);
288
289   return (0);
290 }
291
292 static char *
293 getprogpath(char ret[PATH_MAX], const char *bin)
294 {
295   char *pv, *s, *t, buf[PATH_MAX];
296
297   /* First approach: absolute path. */
298   if (bin[0] == '/') {
299     if (test_dir(buf, ret, "/", bin) == 0)
300       return (ret);
301     return (NULL);
302   }
303
304   /* Second approach: relative path. */
305   if (strchr(bin, '/') != NULL) {
306     if (getcwd(buf, PATH_MAX) == NULL)
307       return (NULL);
308     if (test_dir(buf, ret, buf, bin) == 0)
309       return (ret);
310     return (NULL);
311   }
312
313   /* Third approach: $PATH */
314   if ((pv = getenv("PATH")) == NULL)
315     return (NULL);
316   s = pv = strdup(pv);
317   if (pv == NULL)
318     return (NULL);
319   while ((t = strsep(&s, ":")) != NULL) {
320     if (test_dir(buf, ret, t, bin) == 0) {
321       free(pv);
322       return (ret);
323     }
324   }
325   free(pv);
326   return (NULL);
327 }
328 #endif // __FreeBSD__ || __NetBSD__
329
330 /// GetMainExecutable - Return the path to the main executable, given the
331 /// value of argv[0] from program startup.
332 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
333 #if defined(__APPLE__)
334   // On OS X the executable path is saved to the stack by dyld. Reading it
335   // from there is much faster than calling dladdr, especially for large
336   // binaries with symbols.
337   char exe_path[MAXPATHLEN];
338   uint32_t size = sizeof(exe_path);
339   if (_NSGetExecutablePath(exe_path, &size) == 0) {
340     char link_path[MAXPATHLEN];
341     if (realpath(exe_path, link_path))
342       return Path(link_path);
343   }
344 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__minix)
345   char exe_path[PATH_MAX];
346
347   if (getprogpath(exe_path, argv0) != NULL)
348     return Path(exe_path);
349 #elif defined(__linux__) || defined(__CYGWIN__)
350   char exe_path[MAXPATHLEN];
351   ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path));
352   if (len >= 0)
353     return Path(StringRef(exe_path, len));
354 #elif defined(HAVE_DLFCN_H)
355   // Use dladdr to get executable path if available.
356   Dl_info DLInfo;
357   int err = dladdr(MainAddr, &DLInfo);
358   if (err == 0)
359     return Path();
360
361   // If the filename is a symlink, we need to resolve and return the location of
362   // the actual executable.
363   char link_path[MAXPATHLEN];
364   if (realpath(DLInfo.dli_fname, link_path))
365     return Path(link_path);
366 #else
367 #error GetMainExecutable is not implemented on this host yet.
368 #endif
369   return Path();
370 }
371
372
373 StringRef Path::getDirname() const {
374   return getDirnameCharSep(path, "/");
375 }
376
377 StringRef
378 Path::getBasename() 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(path).substr(slash);
389   else
390     return StringRef(path).substr(slash, dot - slash);
391 }
392
393 StringRef
394 Path::getSuffix() const {
395   // Find the last slash
396   std::string::size_type slash = path.rfind('/');
397   if (slash == std::string::npos)
398     slash = 0;
399   else
400     slash++;
401
402   std::string::size_type dot = path.rfind('.');
403   if (dot == std::string::npos || dot < slash)
404     return StringRef();
405   else
406     return StringRef(path).substr(dot + 1);
407 }
408
409 bool Path::getMagicNumber(std::string &Magic, unsigned len) const {
410   assert(len < 1024 && "Request for magic string too long");
411   char Buf[1025];
412   int fd = ::open(path.c_str(), O_RDONLY);
413   if (fd < 0)
414     return false;
415   ssize_t bytes_read = ::read(fd, Buf, len);
416   ::close(fd);
417   if (ssize_t(len) != bytes_read)
418     return false;
419   Magic.assign(Buf, len);
420   return true;
421 }
422
423 bool
424 Path::exists() const {
425   return 0 == access(path.c_str(), F_OK );
426 }
427
428 bool
429 Path::isDirectory() const {
430   struct stat buf;
431   if (0 != stat(path.c_str(), &buf))
432     return false;
433   return ((buf.st_mode & S_IFMT) == S_IFDIR) ? true : false;
434 }
435
436 bool
437 Path::isSymLink() const {
438   struct stat buf;
439   if (0 != lstat(path.c_str(), &buf))
440     return false;
441   return S_ISLNK(buf.st_mode);
442 }
443
444
445 bool
446 Path::canRead() const {
447   return 0 == access(path.c_str(), R_OK);
448 }
449
450 bool
451 Path::canWrite() const {
452   return 0 == access(path.c_str(), W_OK);
453 }
454
455 bool
456 Path::isRegularFile() const {
457   // Get the status so we can determine if it's a file or directory
458   struct stat buf;
459
460   if (0 != stat(path.c_str(), &buf))
461     return false;
462
463   if (S_ISREG(buf.st_mode))
464     return true;
465
466   return false;
467 }
468
469 bool
470 Path::canExecute() const {
471   if (0 != access(path.c_str(), R_OK | X_OK ))
472     return false;
473   struct stat buf;
474   if (0 != stat(path.c_str(), &buf))
475     return false;
476   if (!S_ISREG(buf.st_mode))
477     return false;
478   return true;
479 }
480
481 StringRef
482 Path::getLast() const {
483   // Find the last slash
484   size_t pos = path.rfind('/');
485
486   // Handle the corner cases
487   if (pos == std::string::npos)
488     return path;
489
490   // If the last character is a slash
491   if (pos == path.length()-1) {
492     // Find the second to last slash
493     size_t pos2 = path.rfind('/', pos-1);
494     if (pos2 == std::string::npos)
495       return StringRef(path).substr(0,pos);
496     else
497       return StringRef(path).substr(pos2+1,pos-pos2-1);
498   }
499   // Return everything after the last slash
500   return StringRef(path).substr(pos+1);
501 }
502
503 const FileStatus *
504 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
505   if (!fsIsValid || update) {
506     struct stat buf;
507     if (0 != stat(path.c_str(), &buf)) {
508       MakeErrMsg(ErrStr, path + ": can't get status of file");
509       return 0;
510     }
511     status.fileSize = buf.st_size;
512     status.modTime.fromEpochTime(buf.st_mtime);
513     status.mode = buf.st_mode;
514     status.user = buf.st_uid;
515     status.group = buf.st_gid;
516     status.uniqueID = uint64_t(buf.st_ino);
517     status.isDir  = S_ISDIR(buf.st_mode);
518     status.isFile = S_ISREG(buf.st_mode);
519     fsIsValid = true;
520   }
521   return &status;
522 }
523
524 static bool AddPermissionBits(const Path &File, int bits) {
525   // Get the umask value from the operating system.  We want to use it
526   // when changing the file's permissions. Since calling umask() sets
527   // the umask and returns its old value, we must call it a second
528   // time to reset it to the user's preference.
529   int mask = umask(0777); // The arg. to umask is arbitrary.
530   umask(mask);            // Restore the umask.
531
532   // Get the file's current mode.
533   struct stat buf;
534   if (0 != stat(File.c_str(), &buf))
535     return false;
536   // Change the file to have whichever permissions bits from 'bits'
537   // that the umask would not disable.
538   if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
539       return false;
540   return true;
541 }
542
543 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
544   if (!AddPermissionBits(*this, 0444))
545     return MakeErrMsg(ErrMsg, path + ": can't make file readable");
546   return false;
547 }
548
549 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
550   if (!AddPermissionBits(*this, 0222))
551     return MakeErrMsg(ErrMsg, path + ": can't make file writable");
552   return false;
553 }
554
555 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
556   if (!AddPermissionBits(*this, 0111))
557     return MakeErrMsg(ErrMsg, path + ": can't make file executable");
558   return false;
559 }
560
561 bool
562 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
563   DIR* direntries = ::opendir(path.c_str());
564   if (direntries == 0)
565     return MakeErrMsg(ErrMsg, path + ": can't open directory");
566
567   std::string dirPath = path;
568   if (!lastIsSlash(dirPath))
569     dirPath += '/';
570
571   result.clear();
572   struct dirent* de = ::readdir(direntries);
573   for ( ; de != 0; de = ::readdir(direntries)) {
574     if (de->d_name[0] != '.') {
575       Path aPath(dirPath + (const char*)de->d_name);
576       struct stat st;
577       if (0 != lstat(aPath.path.c_str(), &st)) {
578         if (S_ISLNK(st.st_mode))
579           continue; // dangling symlink -- ignore
580         return MakeErrMsg(ErrMsg,
581                           aPath.path +  ": can't determine file object type");
582       }
583       result.insert(aPath);
584     }
585   }
586
587   closedir(direntries);
588   return false;
589 }
590
591 bool
592 Path::set(StringRef a_path) {
593   if (a_path.empty())
594     return false;
595   path = a_path;
596   return true;
597 }
598
599 bool
600 Path::appendComponent(StringRef name) {
601   if (name.empty())
602     return false;
603   if (!lastIsSlash(path))
604     path += '/';
605   path += name;
606   return true;
607 }
608
609 bool
610 Path::eraseComponent() {
611   size_t slashpos = path.rfind('/',path.size());
612   if (slashpos == 0 || slashpos == std::string::npos) {
613     path.erase();
614     return true;
615   }
616   if (slashpos == path.size() - 1)
617     slashpos = path.rfind('/',slashpos-1);
618   if (slashpos == std::string::npos) {
619     path.erase();
620     return true;
621   }
622   path.erase(slashpos);
623   return true;
624 }
625
626 bool
627 Path::eraseSuffix() {
628   size_t dotpos = path.rfind('.',path.size());
629   size_t slashpos = path.rfind('/',path.size());
630   if (dotpos != std::string::npos) {
631     if (slashpos == std::string::npos || dotpos > slashpos+1) {
632       path.erase(dotpos, path.size()-dotpos);
633       return true;
634     }
635   }
636   return false;
637 }
638
639 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
640
641   if (access(beg, R_OK | W_OK) == 0)
642     return false;
643
644   if (create_parents) {
645
646     char* c = end;
647
648     for (; c != beg; --c)
649       if (*c == '/') {
650
651         // Recurse to handling the parent directory.
652         *c = '\0';
653         bool x = createDirectoryHelper(beg, c, create_parents);
654         *c = '/';
655
656         // Return if we encountered an error.
657         if (x)
658           return true;
659
660         break;
661       }
662   }
663
664   return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
665 }
666
667 bool
668 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
669   // Get a writeable copy of the path name
670   std::string pathname(path);
671
672   // Null-terminate the last component
673   size_t lastchar = path.length() - 1 ;
674
675   if (pathname[lastchar] != '/')
676     ++lastchar;
677
678   pathname[lastchar] = '\0';
679
680   if (createDirectoryHelper(&pathname[0], &pathname[lastchar], create_parents))
681     return MakeErrMsg(ErrMsg, 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 determine if it's 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   std::string pathname(path);
747   size_t lastchar = path.length() - 1;
748   if (pathname[lastchar] == '/')
749     pathname[lastchar] = '\0';
750   else
751     pathname[lastchar+1] = '\0';
752
753   if (rmdir(pathname.c_str()) != 0)
754     return MakeErrMsg(ErrStr, pathname + ": can't erase directory");
755   return false;
756 }
757
758 bool
759 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
760   if (0 != ::rename(path.c_str(), newName.c_str()))
761     return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
762                newName.str() + "'");
763   return false;
764 }
765
766 bool
767 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
768   struct utimbuf utb;
769   utb.actime = si.modTime.toPosixTime();
770   utb.modtime = utb.actime;
771   if (0 != ::utime(path.c_str(),&utb))
772     return MakeErrMsg(ErrStr, path + ": can't set file modification time");
773   if (0 != ::chmod(path.c_str(),si.mode))
774     return MakeErrMsg(ErrStr, path + ": can't set mode");
775   return false;
776 }
777
778 bool
779 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
780   int inFile = -1;
781   int outFile = -1;
782   inFile = ::open(Src.c_str(), O_RDONLY);
783   if (inFile == -1)
784     return MakeErrMsg(ErrMsg, Src.str() +
785       ": can't open source file to copy");
786
787   outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
788   if (outFile == -1) {
789     ::close(inFile);
790     return MakeErrMsg(ErrMsg, Dest.str() +
791       ": can't create destination file for copy");
792   }
793
794   char Buffer[16*1024];
795   while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
796     if (Amt == -1) {
797       if (errno != EINTR && errno != EAGAIN) {
798         ::close(inFile);
799         ::close(outFile);
800         return MakeErrMsg(ErrMsg, Src.str()+": can't read source file");
801       }
802     } else {
803       char *BufPtr = Buffer;
804       while (Amt) {
805         ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
806         if (AmtWritten == -1) {
807           if (errno != EINTR && errno != EAGAIN) {
808             ::close(inFile);
809             ::close(outFile);
810             return MakeErrMsg(ErrMsg, Dest.str() +
811               ": can't write destination file");
812           }
813         } else {
814           Amt -= AmtWritten;
815           BufPtr += AmtWritten;
816         }
817       }
818     }
819   }
820   ::close(inFile);
821   ::close(outFile);
822   return false;
823 }
824
825 bool
826 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
827   if (reuse_current && !exists())
828     return false; // File doesn't exist already, just use it!
829
830   // Append an XXXXXX pattern to the end of the file for use with mkstemp,
831   // mktemp or our own implementation.
832   // This uses std::vector instead of SmallVector to avoid a dependence on
833   // libSupport. And performance isn't critical here.
834   std::vector<char> Buf;
835   Buf.resize(path.size()+8);
836   char *FNBuffer = &Buf[0];
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   // Try to initialize with unique value.
865   if (FCounter == 0) FCounter = ((unsigned)getpid() & 0xFFFF) << 8;
866   char* pos = strstr(FNBuffer, "XXXXXX");
867   do {
868     if (++FCounter > 0xFFFFFF) {
869       return MakeErrMsg(ErrMsg,
870         path + ": can't make unique filename: too many files");
871     }
872     sprintf(pos, "%06X", FCounter);
873     path = FNBuffer;
874   } while (exists());
875   // POSSIBLE SECURITY BUG: An attacker can easily guess the name and exploit
876   // LLVM.
877 #endif
878   return false;
879 }
880
881 const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
882   int Flags = MAP_PRIVATE;
883 #ifdef MAP_FILE
884   Flags |= MAP_FILE;
885 #endif
886   void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
887   if (BasePtr == MAP_FAILED)
888     return 0;
889   return (const char*)BasePtr;
890 }
891
892 void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
893   ::munmap((void*)BasePtr, FileSize);
894 }
895
896 } // end llvm namespace