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