20d09c0f7ffbbc907a50cab66e34061c15d54c34
[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 "llvm/Config/alloca.h"
20 #include "Unix.h"
21 #if HAVE_SYS_STAT_H
22 #include <sys/stat.h>
23 #endif
24 #if HAVE_FCNTL_H
25 #include <fcntl.h>
26 #endif
27 #ifdef HAVE_SYS_MMAN_H
28 #include <sys/mman.h>
29 #endif
30 #ifdef HAVE_SYS_STAT_H
31 #include <sys/stat.h>
32 #endif
33 #if HAVE_UTIME_H
34 #include <utime.h>
35 #endif
36 #if HAVE_TIME_H
37 #include <time.h>
38 #endif
39 #if HAVE_DIRENT_H
40 # include <dirent.h>
41 # define NAMLEN(dirent) strlen((dirent)->d_name)
42 #else
43 # define dirent direct
44 # define NAMLEN(dirent) (dirent)->d_namlen
45 # if HAVE_SYS_NDIR_H
46 #  include <sys/ndir.h>
47 # endif
48 # if HAVE_SYS_DIR_H
49 #  include <sys/dir.h>
50 # endif
51 # if HAVE_NDIR_H
52 #  include <ndir.h>
53 # endif
54 #endif
55
56 #if HAVE_DLFCN_H
57 #include <dlfcn.h>
58 #endif
59
60 // Put in a hack for Cygwin which falsely reports that the mkdtemp function
61 // is available when it is not.
62 #ifdef __CYGWIN__
63 # undef HAVE_MKDTEMP
64 #endif
65
66 namespace {
67 inline bool lastIsSlash(const std::string& path) {
68   return !path.empty() && path[path.length() - 1] == '/';
69 }
70
71 }
72
73 namespace llvm {
74 using namespace sys;
75
76 extern const char sys::PathSeparator = ':';
77
78 Path::Path(const std::string& p)
79   : path(p) {}
80
81 Path::Path(const char *StrStart, unsigned StrLen)
82   : path(StrStart, StrLen) {}
83
84 bool 
85 Path::isValid() const {
86   // Check some obvious things
87   if (path.empty()) 
88     return false;
89   else if (path.length() >= MAXPATHLEN)
90     return false;
91
92   // Check that the characters are ascii chars
93   size_t len = path.length();
94   unsigned i = 0;
95   while (i < len && isascii(path[i])) 
96     ++i;
97   return i >= len; 
98 }
99
100 bool 
101 Path::isAbsolute() const {
102   if (path.empty())
103     return false;
104   return path[0] == '/';
105
106 Path
107 Path::GetRootDirectory() {
108   Path result;
109   result.set("/");
110   return result;
111 }
112
113 Path
114 Path::GetTemporaryDirectory(std::string* ErrMsg ) {
115 #if defined(HAVE_MKDTEMP)
116   // The best way is with mkdtemp but that's not available on many systems, 
117   // Linux and FreeBSD have it. Others probably won't.
118   char pathname[MAXPATHLEN];
119   strcpy(pathname,"/tmp/llvm_XXXXXX");
120   if (0 == mkdtemp(pathname)) {
121     MakeErrMsg(ErrMsg, 
122       std::string(pathname) + ": can't create temporary directory");
123     return Path();
124   }
125   Path result;
126   result.set(pathname);
127   assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
128   return result;
129 #elif defined(HAVE_MKSTEMP)
130   // If no mkdtemp is available, mkstemp can be used to create a temporary file
131   // which is then removed and created as a directory. We prefer this over
132   // mktemp because of mktemp's inherent security and threading risks. We still
133   // have a slight race condition from the time the temporary file is created to
134   // the time it is re-created as a directoy. 
135   char pathname[MAXPATHLEN];
136   strcpy(pathname, "/tmp/llvm_XXXXXX");
137   int fd = 0;
138   if (-1 == (fd = mkstemp(pathname))) {
139     MakeErrMsg(ErrMsg, 
140       std::string(pathname) + ": can't create temporary directory");
141     return Path();
142   }
143   ::close(fd);
144   ::unlink(pathname); // start race condition, ignore errors
145   if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
146     MakeErrMsg(ErrMsg, 
147       std::string(pathname) + ": can't create temporary directory");
148     return Path();
149   }
150   Path result;
151   result.set(pathname);
152   assert(result.isValid() && "mkstemp didn't create a valid pathname!");
153   return result;
154 #elif defined(HAVE_MKTEMP)
155   // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
156   // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
157   // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
158   // the XXXXXX with the pid of the process and a letter. That leads to only
159   // twenty six temporary files that can be generated.
160   char pathname[MAXPATHLEN];
161   strcpy(pathname, "/tmp/llvm_XXXXXX");
162   char *TmpName = ::mktemp(pathname);
163   if (TmpName == 0) {
164     MakeErrMsg(ErrMsg, 
165       std::string(TmpName) + ": can't create unique directory name");
166     return Path();
167   }
168   if (-1 == ::mkdir(TmpName, S_IRWXU)) {
169     MakeErrMsg(ErrMsg, 
170         std::string(TmpName) + ": can't create temporary directory");
171     return Path();
172   }
173   Path result;
174   result.set(TmpName);
175   assert(result.isValid() && "mktemp didn't create a valid pathname!");
176   return result;
177 #else
178   // This is the worst case implementation. tempnam(3) leaks memory unless its
179   // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
180   // issues. The mktemp(3) function doesn't have enough variability in the
181   // temporary name generated. So, we provide our own implementation that 
182   // increments an integer from a random number seeded by the current time. This
183   // should be sufficiently unique that we don't have many collisions between
184   // processes. Generally LLVM processes don't run very long and don't use very
185   // many temporary files so this shouldn't be a big issue for LLVM.
186   static time_t num = ::time(0);
187   char pathname[MAXPATHLEN];
188   do {
189     num++;
190     sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
191   } while ( 0 == access(pathname, F_OK ) );
192   if (-1 == ::mkdir(pathname, S_IRWXU)) {
193     MakeErrMsg(ErrMsg, 
194       std::string(pathname) + ": can't create temporary directory");
195     return Path();
196   }
197   Path result;
198   result.set(pathname);
199   assert(result.isValid() && "mkstemp didn't create a valid pathname!");
200   return result;
201 #endif
202 }
203
204 void 
205 Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
206 #ifdef LTDL_SHLIBPATH_VAR
207   char* env_var = getenv(LTDL_SHLIBPATH_VAR);
208   if (env_var != 0) {
209     getPathList(env_var,Paths);
210   }
211 #endif
212   // FIXME: Should this look at LD_LIBRARY_PATH too?
213   Paths.push_back(sys::Path("/usr/local/lib/"));
214   Paths.push_back(sys::Path("/usr/X11R6/lib/"));
215   Paths.push_back(sys::Path("/usr/lib/"));
216   Paths.push_back(sys::Path("/lib/"));
217 }
218
219 void
220 Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
221   char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
222   if (env_var != 0) {
223     getPathList(env_var,Paths);
224   }
225 #ifdef LLVM_LIBDIR
226   {
227     Path tmpPath;
228     if (tmpPath.set(LLVM_LIBDIR))
229       if (tmpPath.canRead())
230         Paths.push_back(tmpPath);
231   }
232 #endif
233   GetSystemLibraryPaths(Paths);
234 }
235
236 Path 
237 Path::GetLLVMDefaultConfigDir() {
238   return Path("/etc/llvm/");
239 }
240
241 Path
242 Path::GetUserHomeDirectory() {
243   const char* home = getenv("HOME");
244   if (home) {
245     Path result;
246     if (result.set(home))
247       return result;
248   }
249   return GetRootDirectory();
250 }
251
252 Path
253 Path::GetCurrentDirectory() {
254   char pathname[MAXPATHLEN];
255   if (!getcwd(pathname,MAXPATHLEN)) {
256     assert (false && "Could not query current working directory.");
257     return Path("");
258   }
259   
260   return Path(pathname);
261 }
262
263 /// GetMainExecutable - Return the path to the main executable, given the
264 /// value of argv[0] from program startup.
265 Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
266 #if defined(__CYGWIN__)
267   char exe_link[64];
268   snprintf(exe_link, sizeof(exe_link), "/proc/%d/exe", getpid());
269   char exe_path[MAXPATHLEN];
270   ssize_t len = readlink(exe_link, exe_path, sizeof(exe_path));
271   if (len > 0 && len < MAXPATHLEN - 1) {
272     exe_path[len] = '\0';
273     return Path(std::string(exe_path));
274   }
275 #elif defined(HAVE_DLFCN_H)
276   // Use dladdr to get executable path if available.
277   Dl_info DLInfo;
278   int err = dladdr(MainAddr, &DLInfo);
279   if (err != 0)
280     return Path(std::string(DLInfo.dli_fname));
281 #endif
282   return Path();
283 }
284
285
286 std::string Path::getDirname() const {
287   return getDirnameCharSep(path, '/');
288 }
289
290 std::string
291 Path::getBasename() const {
292   // Find the last slash
293   std::string::size_type slash = path.rfind('/');
294   if (slash == std::string::npos)
295     slash = 0;
296   else
297     slash++;
298
299   std::string::size_type dot = path.rfind('.');
300   if (dot == std::string::npos || dot < slash)
301     return path.substr(slash);
302   else
303     return path.substr(slash, dot - slash);
304 }
305
306 std::string
307 Path::getSuffix() const {
308   // Find the last slash
309   std::string::size_type slash = path.rfind('/');
310   if (slash == std::string::npos)
311     slash = 0;
312   else
313     slash++;
314
315   std::string::size_type dot = path.rfind('.');
316   if (dot == std::string::npos || dot < slash)
317     return std::string();
318   else
319     return path.substr(dot + 1);
320 }
321
322 bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
323   assert(len < 1024 && "Request for magic string too long");
324   char* buf = (char*) alloca(1 + len);
325   int fd = ::open(path.c_str(), O_RDONLY);
326   if (fd < 0)
327     return false;
328   ssize_t bytes_read = ::read(fd, buf, len);
329   ::close(fd);
330   if (ssize_t(len) != bytes_read) {
331     Magic.clear();
332     return false;
333   }
334   Magic.assign(buf,len);
335   return true;
336 }
337
338 bool
339 Path::exists() const {
340   return 0 == access(path.c_str(), F_OK );
341 }
342
343 bool
344 Path::isDirectory() const {
345   struct stat buf;
346   if (0 != stat(path.c_str(), &buf))
347     return false;
348   return buf.st_mode & S_IFDIR ? true : false;
349 }
350
351 bool
352 Path::canRead() const {
353   return 0 == access(path.c_str(), F_OK | R_OK );
354 }
355
356 bool
357 Path::canWrite() const {
358   return 0 == access(path.c_str(), F_OK | W_OK );
359 }
360
361 bool
362 Path::canExecute() const {
363   if (0 != access(path.c_str(), R_OK | X_OK ))
364     return false;
365   struct stat buf;
366   if (0 != stat(path.c_str(), &buf))
367     return false;
368   if (!S_ISREG(buf.st_mode))
369     return false;
370   return true;
371 }
372
373 std::string 
374 Path::getLast() const {
375   // Find the last slash
376   size_t pos = path.rfind('/');
377
378   // Handle the corner cases
379   if (pos == std::string::npos)
380     return path;
381
382   // If the last character is a slash
383   if (pos == path.length()-1) {
384     // Find the second to last slash
385     size_t pos2 = path.rfind('/', pos-1);
386     if (pos2 == std::string::npos)
387       return path.substr(0,pos);
388     else
389       return path.substr(pos2+1,pos-pos2-1);
390   }
391   // Return everything after the last slash
392   return path.substr(pos+1);
393 }
394
395 const FileStatus *
396 PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
397   if (!fsIsValid || update) {
398     struct stat buf;
399     if (0 != stat(path.c_str(), &buf)) {
400       MakeErrMsg(ErrStr, path + ": can't get status of file");
401       return 0;
402     }
403     status.fileSize = buf.st_size;
404     status.modTime.fromEpochTime(buf.st_mtime);
405     status.mode = buf.st_mode;
406     status.user = buf.st_uid;
407     status.group = buf.st_gid;
408     status.uniqueID = uint64_t(buf.st_ino);
409     status.isDir  = S_ISDIR(buf.st_mode);
410     status.isFile = S_ISREG(buf.st_mode);
411     fsIsValid = true;
412   }
413   return &status;
414 }
415
416 static bool AddPermissionBits(const Path &File, int bits) {
417   // Get the umask value from the operating system.  We want to use it
418   // when changing the file's permissions. Since calling umask() sets
419   // the umask and returns its old value, we must call it a second
420   // time to reset it to the user's preference.
421   int mask = umask(0777); // The arg. to umask is arbitrary.
422   umask(mask);            // Restore the umask.
423
424   // Get the file's current mode.
425   struct stat buf;
426   if (0 != stat(File.toString().c_str(), &buf)) 
427     return false;
428   // Change the file to have whichever permissions bits from 'bits'
429   // that the umask would not disable.
430   if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
431       return false;
432   return true;
433 }
434
435 bool Path::makeReadableOnDisk(std::string* ErrMsg) {
436   if (!AddPermissionBits(*this, 0444)) 
437     return MakeErrMsg(ErrMsg, path + ": can't make file readable");
438   return false;
439 }
440
441 bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
442   if (!AddPermissionBits(*this, 0222))
443     return MakeErrMsg(ErrMsg, path + ": can't make file writable");
444   return false;
445 }
446
447 bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
448   if (!AddPermissionBits(*this, 0111))
449     return MakeErrMsg(ErrMsg, path + ": can't make file executable");
450   return false;
451 }
452
453 bool
454 Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
455   DIR* direntries = ::opendir(path.c_str());
456   if (direntries == 0)
457     return MakeErrMsg(ErrMsg, path + ": can't open directory");
458
459   std::string dirPath = path;
460   if (!lastIsSlash(dirPath))
461     dirPath += '/';
462
463   result.clear();
464   struct dirent* de = ::readdir(direntries);
465   for ( ; de != 0; de = ::readdir(direntries)) {
466     if (de->d_name[0] != '.') {
467       Path aPath(dirPath + (const char*)de->d_name);
468       struct stat st;
469       if (0 != lstat(aPath.path.c_str(), &st)) {
470         if (S_ISLNK(st.st_mode))
471           continue; // dangling symlink -- ignore
472         return MakeErrMsg(ErrMsg, 
473                           aPath.path +  ": can't determine file object type");
474       }
475       result.insert(aPath);
476     }
477   }
478   
479   closedir(direntries);
480   return false;
481 }
482
483 bool
484 Path::set(const std::string& a_path) {
485   if (a_path.empty())
486     return false;
487   std::string save(path);
488   path = a_path;
489   if (!isValid()) {
490     path = save;
491     return false;
492   }
493   return true;
494 }
495
496 bool
497 Path::appendComponent(const std::string& name) {
498   if (name.empty())
499     return false;
500   std::string save(path);
501   if (!lastIsSlash(path))
502     path += '/';
503   path += name;
504   if (!isValid()) {
505     path = save;
506     return false;
507   }
508   return true;
509 }
510
511 bool
512 Path::eraseComponent() {
513   size_t slashpos = path.rfind('/',path.size());
514   if (slashpos == 0 || slashpos == std::string::npos) {
515     path.erase();
516     return true;
517   }
518   if (slashpos == path.size() - 1)
519     slashpos = path.rfind('/',slashpos-1);
520   if (slashpos == std::string::npos) {
521     path.erase();
522     return true;
523   }
524   path.erase(slashpos);
525   return true;
526 }
527
528 bool
529 Path::appendSuffix(const std::string& suffix) {
530   std::string save(path);
531   path.append(".");
532   path.append(suffix);
533   if (!isValid()) {
534     path = save;
535     return false;
536   }
537   return true;
538 }
539
540 bool
541 Path::eraseSuffix() {
542   std::string save = path;
543   size_t dotpos = path.rfind('.',path.size());
544   size_t slashpos = path.rfind('/',path.size());
545   if (dotpos != std::string::npos) {
546     if (slashpos == std::string::npos || dotpos > slashpos+1) {
547       path.erase(dotpos, path.size()-dotpos);
548       return true;
549     }
550   }
551   if (!isValid())
552     path = save;
553   return false;
554 }
555
556 static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
557   
558   if (access(beg, F_OK | R_OK | W_OK) == 0)
559     return false;
560     
561   if (create_parents) {
562     
563     char* c = end;
564         
565     for (; c != beg; --c)
566       if (*c == '/') {
567         
568         // Recurse to handling the parent directory.
569         *c = '\0';          
570         bool x = createDirectoryHelper(beg, c, create_parents);
571         *c = '/';
572         
573         // Return if we encountered an error.
574         if (x)
575           return true;
576           
577         break;
578       }
579   }      
580   
581   return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
582 }
583
584 bool
585 Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
586   // Get a writeable copy of the path name
587   char pathname[MAXPATHLEN];
588   path.copy(pathname,MAXPATHLEN);
589
590   // Null-terminate the last component
591   size_t lastchar = path.length() - 1 ;
592   
593   if (pathname[lastchar] != '/')
594     ++lastchar;
595     
596   pathname[lastchar] = 0;
597     
598   if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
599     return MakeErrMsg(ErrMsg, 
600                       std::string(pathname) + ": can't create directory");
601   
602   return false;
603 }
604
605 bool
606 Path::createFileOnDisk(std::string* ErrMsg) {
607   // Create the file
608   int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
609   if (fd < 0)
610     return MakeErrMsg(ErrMsg, path + ": can't create file");
611   ::close(fd);
612   return false;
613 }
614
615 bool
616 Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
617   // Make this into a unique file name
618   if (makeUnique( reuse_current, ErrMsg ))
619     return true;
620
621   // create the file
622   int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
623   if (fd < 0) 
624     return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
625   ::close(fd);
626   return false;
627 }
628
629 bool
630 Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
631   // Get the status so we can determin if its a file or directory
632   struct stat buf;
633   if (0 != stat(path.c_str(), &buf)) {
634     MakeErrMsg(ErrStr, path + ": can't get status of file");
635     return true;
636   }
637
638   // Note: this check catches strange situations. In all cases, LLVM should 
639   // only be involved in the creation and deletion of regular files.  This 
640   // check ensures that what we're trying to erase is a regular file. It 
641   // effectively prevents LLVM from erasing things like /dev/null, any block 
642   // special file, or other things that aren't "regular" files. 
643   if (S_ISREG(buf.st_mode)) {
644     if (unlink(path.c_str()) != 0)
645       return MakeErrMsg(ErrStr, path + ": can't destroy file");
646     return false;
647   }
648   
649   if (!S_ISDIR(buf.st_mode)) {
650     if (ErrStr) *ErrStr = "not a file or directory";
651     return true;
652   }
653
654   if (remove_contents) {
655     // Recursively descend the directory to remove its contents.
656     std::string cmd = "/bin/rm -rf " + path;
657     system(cmd.c_str());
658     return false;
659   }
660
661   // Otherwise, try to just remove the one directory.
662   char pathname[MAXPATHLEN];
663   path.copy(pathname, MAXPATHLEN);
664   size_t lastchar = path.length() - 1;
665   if (pathname[lastchar] == '/') 
666     pathname[lastchar] = 0;
667   else
668     pathname[lastchar+1] = 0;
669     
670   if (rmdir(pathname) != 0)
671     return MakeErrMsg(ErrStr, 
672       std::string(pathname) + ": can't erase directory");
673   return false;
674 }
675
676 bool
677 Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
678   if (0 != ::rename(path.c_str(), newName.c_str()))
679     return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" + 
680                newName.toString() + "' ");
681   return false;
682 }
683
684 bool 
685 Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
686   struct utimbuf utb;
687   utb.actime = si.modTime.toPosixTime();
688   utb.modtime = utb.actime;
689   if (0 != ::utime(path.c_str(),&utb))
690     return MakeErrMsg(ErrStr, path + ": can't set file modification time");
691   if (0 != ::chmod(path.c_str(),si.mode))
692     return MakeErrMsg(ErrStr, path + ": can't set mode");
693   return false;
694 }
695
696 bool 
697 sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
698   int inFile = -1;
699   int outFile = -1;
700   inFile = ::open(Src.c_str(), O_RDONLY);
701   if (inFile == -1)
702     return MakeErrMsg(ErrMsg, Src.toString() + 
703       ": can't open source file to copy");
704
705   outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
706   if (outFile == -1) {
707     ::close(inFile);
708     return MakeErrMsg(ErrMsg, Dest.toString() +
709       ": can't create destination file for copy");
710   }
711
712   char Buffer[16*1024];
713   while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
714     if (Amt == -1) {
715       if (errno != EINTR && errno != EAGAIN) {
716         ::close(inFile);
717         ::close(outFile);
718         return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file: ");
719       }
720     } else {
721       char *BufPtr = Buffer;
722       while (Amt) {
723         ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
724         if (AmtWritten == -1) {
725           if (errno != EINTR && errno != EAGAIN) {
726             ::close(inFile);
727             ::close(outFile);
728             return MakeErrMsg(ErrMsg, Dest.toString() + 
729               ": can't write destination file: ");
730           }
731         } else {
732           Amt -= AmtWritten;
733           BufPtr += AmtWritten;
734         }
735       }
736     }
737   }
738   ::close(inFile);
739   ::close(outFile);
740   return false;
741 }
742
743 bool 
744 Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
745   if (reuse_current && !exists())
746     return false; // File doesn't exist already, just use it!
747
748   // Append an XXXXXX pattern to the end of the file for use with mkstemp, 
749   // mktemp or our own implementation.
750   char *FNBuffer = (char*) alloca(path.size()+8);
751   path.copy(FNBuffer,path.size());
752   strcpy(FNBuffer+path.size(), "-XXXXXX");
753
754 #if defined(HAVE_MKSTEMP)
755   int TempFD;
756   if ((TempFD = mkstemp(FNBuffer)) == -1)
757     return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
758
759   // We don't need to hold the temp file descriptor... we will trust that no one
760   // will overwrite/delete the file before we can open it again.
761   close(TempFD);
762
763   // Save the name
764   path = FNBuffer;
765 #elif defined(HAVE_MKTEMP)
766   // If we don't have mkstemp, use the old and obsolete mktemp function.
767   if (mktemp(FNBuffer) == 0)
768     return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
769
770   // Save the name
771   path = FNBuffer;
772 #else
773   // Okay, looks like we have to do it all by our lonesome.
774   static unsigned FCounter = 0;
775   unsigned offset = path.size() + 1;
776   while ( FCounter < 999999 && exists()) {
777     sprintf(FNBuffer+offset,"%06u",++FCounter);
778     path = FNBuffer;
779   }
780   if (FCounter > 999999)
781     return MakeErrMsg(ErrMsg, 
782       path + ": can't make unique filename: too many files");
783 #endif
784   return false;
785 }
786
787 const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
788   int Flags = MAP_PRIVATE;
789 #ifdef MAP_FILE
790   Flags |= MAP_FILE;
791 #endif
792   void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
793   if (BasePtr == MAP_FAILED)
794     return 0;
795   return (const char*)BasePtr;
796 }
797
798 void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
799   ::munmap((void*)BasePtr, FileSize);
800 }
801
802 } // end llvm namespace
803