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