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