Remove dead or useless header checks from cmake and autoconf
[oota-llvm.git] / lib / Support / Unix / Path.inc
1 //===- llvm/Support/Unix/Path.inc - 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 implementation of the Path API.
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 #include "llvm/Support/Process.h"
21 #include <limits.h>
22 #include <stdio.h>
23 #if HAVE_SYS_STAT_H
24 #include <sys/stat.h>
25 #endif
26 #if HAVE_FCNTL_H
27 #include <fcntl.h>
28 #endif
29 #ifdef HAVE_SYS_MMAN_H
30 #include <sys/mman.h>
31 #endif
32 #if HAVE_DIRENT_H
33 # include <dirent.h>
34 # define NAMLEN(dirent) strlen((dirent)->d_name)
35 #else
36 # define dirent direct
37 # define NAMLEN(dirent) (dirent)->d_namlen
38 # if HAVE_SYS_NDIR_H
39 #  include <sys/ndir.h>
40 # endif
41 # if HAVE_SYS_DIR_H
42 #  include <sys/dir.h>
43 # endif
44 # if HAVE_NDIR_H
45 #  include <ndir.h>
46 # endif
47 #endif
48
49 #ifdef __APPLE__
50 #include <mach-o/dyld.h>
51 #endif
52
53 // Both stdio.h and cstdio are included via different pathes and
54 // stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
55 // either.
56 #undef ferror
57 #undef feof
58
59 // For GNU Hurd
60 #if defined(__GNU__) && !defined(PATH_MAX)
61 # define PATH_MAX 4096
62 #endif
63
64 using namespace llvm;
65
66 namespace {
67   /// This class automatically closes the given file descriptor when it goes out
68   /// of scope. You can take back explicit ownership of the file descriptor by
69   /// calling take(). The destructor does not verify that close was successful.
70   /// Therefore, never allow this class to call close on a file descriptor that
71   /// has been read from or written to.
72   struct AutoFD {
73     int FileDescriptor;
74
75     AutoFD(int fd) : FileDescriptor(fd) {}
76     ~AutoFD() {
77       if (FileDescriptor >= 0)
78         ::close(FileDescriptor);
79     }
80
81     int take() {
82       int ret = FileDescriptor;
83       FileDescriptor = -1;
84       return ret;
85     }
86
87     operator int() const {return FileDescriptor;}
88   };
89
90   error_code TempDir(SmallVectorImpl<char> &result) {
91     // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
92     const char *dir = 0;
93     (dir = std::getenv("TMPDIR" )) ||
94     (dir = std::getenv("TMP"    )) ||
95     (dir = std::getenv("TEMP"   )) ||
96     (dir = std::getenv("TEMPDIR")) ||
97 #ifdef P_tmpdir
98     (dir = P_tmpdir) ||
99 #endif
100     (dir = "/tmp");
101
102     result.clear();
103     StringRef d(dir);
104     result.append(d.begin(), d.end());
105     return error_code::success();
106   }
107 }
108
109 static error_code createUniqueEntity(const Twine &Model, int &ResultFD,
110                                      SmallVectorImpl<char> &ResultPath,
111                                      bool MakeAbsolute, unsigned Mode,
112                                      FSEntity Type) {
113   SmallString<128> ModelStorage;
114   Model.toVector(ModelStorage);
115
116   if (MakeAbsolute) {
117     // Make model absolute by prepending a temp directory if it's not already.
118     bool absolute = sys::path::is_absolute(Twine(ModelStorage));
119     if (!absolute) {
120       SmallString<128> TDir;
121       if (error_code ec = TempDir(TDir)) return ec;
122       sys::path::append(TDir, Twine(ModelStorage));
123       ModelStorage.swap(TDir);
124     }
125   }
126
127   // From here on, DO NOT modify model. It may be needed if the randomly chosen
128   // path already exists.
129   ResultPath = ModelStorage;
130   // Null terminate.
131   ResultPath.push_back(0);
132   ResultPath.pop_back();
133
134 retry_random_path:
135   // Replace '%' with random chars.
136   for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
137     if (ModelStorage[i] == '%')
138       ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
139   }
140
141   // Try to open + create the file.
142   switch (Type) {
143   case FS_File: {
144     int RandomFD = ::open(ResultPath.begin(), O_RDWR | O_CREAT | O_EXCL, Mode);
145     if (RandomFD == -1) {
146       int SavedErrno = errno;
147       // If the file existed, try again, otherwise, error.
148       if (SavedErrno == errc::file_exists)
149         goto retry_random_path;
150       return error_code(SavedErrno, system_category());
151     }
152
153     ResultFD = RandomFD;
154     return error_code::success();
155   }
156
157   case FS_Name: {
158     bool Exists;
159     error_code EC = sys::fs::exists(ResultPath.begin(), Exists);
160     if (EC)
161       return EC;
162     if (Exists)
163       goto retry_random_path;
164     return error_code::success();
165   }
166
167   case FS_Dir: {
168     bool Existed;
169     error_code EC = sys::fs::create_directory(ResultPath.begin(), Existed);
170     if (EC)
171       return EC;
172     if (Existed)
173       goto retry_random_path;
174     return error_code::success();
175   }
176   }
177   llvm_unreachable("Invalid Type");
178 }
179
180 namespace llvm {
181 namespace sys  {
182 namespace fs {
183 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
184     defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
185     defined(__linux__) || defined(__CYGWIN__)
186 static int
187 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
188     const char *dir, const char *bin)
189 {
190   struct stat sb;
191
192   snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
193   if (realpath(buf, ret) == NULL)
194     return (1);
195   if (stat(buf, &sb) != 0)
196     return (1);
197
198   return (0);
199 }
200
201 static char *
202 getprogpath(char ret[PATH_MAX], const char *bin)
203 {
204   char *pv, *s, *t, buf[PATH_MAX];
205
206   /* First approach: absolute path. */
207   if (bin[0] == '/') {
208     if (test_dir(buf, ret, "/", bin) == 0)
209       return (ret);
210     return (NULL);
211   }
212
213   /* Second approach: relative path. */
214   if (strchr(bin, '/') != NULL) {
215     if (getcwd(buf, PATH_MAX) == NULL)
216       return (NULL);
217     if (test_dir(buf, ret, buf, bin) == 0)
218       return (ret);
219     return (NULL);
220   }
221
222   /* Third approach: $PATH */
223   if ((pv = getenv("PATH")) == NULL)
224     return (NULL);
225   s = pv = strdup(pv);
226   if (pv == NULL)
227     return (NULL);
228   while ((t = strsep(&s, ":")) != NULL) {
229     if (test_dir(buf, ret, t, bin) == 0) {
230       free(pv);
231       return (ret);
232     }
233   }
234   free(pv);
235   return (NULL);
236 }
237 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
238
239 /// GetMainExecutable - Return the path to the main executable, given the
240 /// value of argv[0] from program startup.
241 std::string getMainExecutable(const char *argv0, void *MainAddr) {
242 #if defined(__APPLE__)
243   // On OS X the executable path is saved to the stack by dyld. Reading it
244   // from there is much faster than calling dladdr, especially for large
245   // binaries with symbols.
246   char exe_path[MAXPATHLEN];
247   uint32_t size = sizeof(exe_path);
248   if (_NSGetExecutablePath(exe_path, &size) == 0) {
249     char link_path[MAXPATHLEN];
250     if (realpath(exe_path, link_path))
251       return link_path;
252   }
253 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
254       defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__)
255   char exe_path[PATH_MAX];
256
257   if (getprogpath(exe_path, argv0) != NULL)
258     return exe_path;
259 #elif defined(__linux__) || defined(__CYGWIN__)
260   char exe_path[MAXPATHLEN];
261   StringRef aPath("/proc/self/exe");
262   if (sys::fs::exists(aPath)) {
263       // /proc is not always mounted under Linux (chroot for example).
264       ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
265       if (len >= 0)
266           return StringRef(exe_path, len);
267   } else {
268       // Fall back to the classical detection.
269       if (getprogpath(exe_path, argv0) != NULL)
270           return exe_path;
271   }
272 #elif defined(HAVE_DLFCN_H)
273   // Use dladdr to get executable path if available.
274   Dl_info DLInfo;
275   int err = dladdr(MainAddr, &DLInfo);
276   if (err == 0)
277     return "";
278
279   // If the filename is a symlink, we need to resolve and return the location of
280   // the actual executable.
281   char link_path[MAXPATHLEN];
282   if (realpath(DLInfo.dli_fname, link_path))
283     return link_path;
284 #else
285 #error GetMainExecutable is not implemented on this host yet.
286 #endif
287   return "";
288 }
289
290 TimeValue file_status::getLastModificationTime() const {
291   TimeValue Ret;
292   Ret.fromEpochTime(fs_st_mtime);
293   return Ret;
294 }
295
296 error_code current_path(SmallVectorImpl<char> &result) {
297 #ifdef MAXPATHLEN
298   result.reserve(MAXPATHLEN);
299 #else
300 // For GNU Hurd
301   result.reserve(1024);
302 #endif
303
304   while (true) {
305     if (::getcwd(result.data(), result.capacity()) == 0) {
306       // See if there was a real error.
307       if (errno != errc::not_enough_memory)
308         return error_code(errno, system_category());
309       // Otherwise there just wasn't enough space.
310       result.reserve(result.capacity() * 2);
311     } else
312       break;
313   }
314
315   result.set_size(strlen(result.data()));
316   return error_code::success();
317 }
318
319 error_code create_directory(const Twine &path, bool &existed) {
320   SmallString<128> path_storage;
321   StringRef p = path.toNullTerminatedStringRef(path_storage);
322
323   if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
324     if (errno != errc::file_exists)
325       return error_code(errno, system_category());
326     existed = true;
327   } else
328     existed = false;
329
330   return error_code::success();
331 }
332
333 error_code create_hard_link(const Twine &to, const Twine &from) {
334   // Get arguments.
335   SmallString<128> from_storage;
336   SmallString<128> to_storage;
337   StringRef f = from.toNullTerminatedStringRef(from_storage);
338   StringRef t = to.toNullTerminatedStringRef(to_storage);
339
340   if (::link(t.begin(), f.begin()) == -1)
341     return error_code(errno, system_category());
342
343   return error_code::success();
344 }
345
346 error_code create_symlink(const Twine &to, const Twine &from) {
347   // Get arguments.
348   SmallString<128> from_storage;
349   SmallString<128> to_storage;
350   StringRef f = from.toNullTerminatedStringRef(from_storage);
351   StringRef t = to.toNullTerminatedStringRef(to_storage);
352
353   if (::symlink(t.begin(), f.begin()) == -1)
354     return error_code(errno, system_category());
355
356   return error_code::success();
357 }
358
359 error_code remove(const Twine &path, bool &existed) {
360   SmallString<128> path_storage;
361   StringRef p = path.toNullTerminatedStringRef(path_storage);
362
363   struct stat buf;
364   if (stat(p.begin(), &buf) != 0) {
365     if (errno != errc::no_such_file_or_directory)
366       return error_code(errno, system_category());
367     existed = false;
368     return error_code::success();
369   }
370
371   // Note: this check catches strange situations. In all cases, LLVM should
372   // only be involved in the creation and deletion of regular files.  This
373   // check ensures that what we're trying to erase is a regular file. It
374   // effectively prevents LLVM from erasing things like /dev/null, any block
375   // special file, or other things that aren't "regular" files.
376   if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
377     return make_error_code(errc::operation_not_permitted);
378
379   if (::remove(p.begin()) == -1) {
380     if (errno != errc::no_such_file_or_directory)
381       return error_code(errno, system_category());
382     existed = false;
383   } else
384     existed = true;
385
386   return error_code::success();
387 }
388
389 error_code rename(const Twine &from, const Twine &to) {
390   // Get arguments.
391   SmallString<128> from_storage;
392   SmallString<128> to_storage;
393   StringRef f = from.toNullTerminatedStringRef(from_storage);
394   StringRef t = to.toNullTerminatedStringRef(to_storage);
395
396   if (::rename(f.begin(), t.begin()) == -1)
397     return error_code(errno, system_category());
398
399   return error_code::success();
400 }
401
402 error_code resize_file(const Twine &path, uint64_t size) {
403   SmallString<128> path_storage;
404   StringRef p = path.toNullTerminatedStringRef(path_storage);
405
406   if (::truncate(p.begin(), size) == -1)
407     return error_code(errno, system_category());
408
409   return error_code::success();
410 }
411
412 error_code exists(const Twine &path, bool &result) {
413   SmallString<128> path_storage;
414   StringRef p = path.toNullTerminatedStringRef(path_storage);
415
416   if (::access(p.begin(), F_OK) == -1) {
417     if (errno != errc::no_such_file_or_directory)
418       return error_code(errno, system_category());
419     result = false;
420   } else
421     result = true;
422
423   return error_code::success();
424 }
425
426 bool can_write(const Twine &Path) {
427   SmallString<128> PathStorage;
428   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
429   return 0 == access(P.begin(), W_OK);
430 }
431
432 bool can_execute(const Twine &Path) {
433   SmallString<128> PathStorage;
434   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
435
436   if (0 != access(P.begin(), R_OK | X_OK))
437     return false;
438   struct stat buf;
439   if (0 != stat(P.begin(), &buf))
440     return false;
441   if (!S_ISREG(buf.st_mode))
442     return false;
443   return true;
444 }
445
446 bool equivalent(file_status A, file_status B) {
447   assert(status_known(A) && status_known(B));
448   return A.fs_st_dev == B.fs_st_dev &&
449          A.fs_st_ino == B.fs_st_ino;
450 }
451
452 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
453   file_status fsA, fsB;
454   if (error_code ec = status(A, fsA)) return ec;
455   if (error_code ec = status(B, fsB)) return ec;
456   result = equivalent(fsA, fsB);
457   return error_code::success();
458 }
459
460 error_code getUniqueID(const Twine Path, uint64_t &Result) {
461   SmallString<128> Storage;
462   StringRef P = Path.toNullTerminatedStringRef(Storage);
463
464   struct stat Status;
465   if (::stat(P.begin(), &Status) != 0)
466     return error_code(errno, system_category());
467
468   Result = Status.st_ino;
469   return error_code::success();
470 }
471
472 static error_code fillStatus(int StatRet, const struct stat &Status,
473                              file_status &Result) {
474   if (StatRet != 0) {
475     error_code ec(errno, system_category());
476     if (ec == errc::no_such_file_or_directory)
477       Result = file_status(file_type::file_not_found);
478     else
479       Result = file_status(file_type::status_error);
480     return ec;
481   }
482
483   file_type Type = file_type::type_unknown;
484
485   if (S_ISDIR(Status.st_mode))
486     Type = file_type::directory_file;
487   else if (S_ISREG(Status.st_mode))
488     Type = file_type::regular_file;
489   else if (S_ISBLK(Status.st_mode))
490     Type = file_type::block_file;
491   else if (S_ISCHR(Status.st_mode))
492     Type = file_type::character_file;
493   else if (S_ISFIFO(Status.st_mode))
494     Type = file_type::fifo_file;
495   else if (S_ISSOCK(Status.st_mode))
496     Type = file_type::socket_file;
497
498   perms Perms = static_cast<perms>(Status.st_mode);
499   Result =
500       file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
501                   Status.st_uid, Status.st_gid, Status.st_size);
502
503   return error_code::success();
504 }
505
506 error_code status(const Twine &Path, file_status &Result) {
507   SmallString<128> PathStorage;
508   StringRef P = Path.toNullTerminatedStringRef(PathStorage);
509
510   struct stat Status;
511   int StatRet = ::stat(P.begin(), &Status);
512   return fillStatus(StatRet, Status, Result);
513 }
514
515 error_code status(int FD, file_status &Result) {
516   struct stat Status;
517   int StatRet = ::fstat(FD, &Status);
518   return fillStatus(StatRet, Status, Result);
519 }
520
521 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
522 #if defined(HAVE_FUTIMENS)
523   timespec Times[2];
524   Times[0].tv_sec = Time.toPosixTime();
525   Times[0].tv_nsec = 0;
526   Times[1] = Times[0];
527   if (::futimens(FD, Times))
528 #elif defined(HAVE_FUTIMES)
529   timeval Times[2];
530   Times[0].tv_sec = Time.toPosixTime();
531   Times[0].tv_usec = 0;
532   Times[1] = Times[0];
533   if (::futimes(FD, Times))
534 #else
535 #error Missing futimes() and futimens()
536 #endif
537     return error_code(errno, system_category());
538   return error_code::success();
539 }
540
541 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
542   AutoFD ScopedFD(FD);
543   if (!CloseFD)
544     ScopedFD.take();
545
546   // Figure out how large the file is.
547   struct stat FileInfo;
548   if (fstat(FD, &FileInfo) == -1)
549     return error_code(errno, system_category());
550   uint64_t FileSize = FileInfo.st_size;
551
552   if (Size == 0)
553     Size = FileSize;
554   else if (FileSize < Size) {
555     // We need to grow the file.
556     if (ftruncate(FD, Size) == -1)
557       return error_code(errno, system_category());
558   }
559
560   int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
561   int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
562 #ifdef MAP_FILE
563   flags |= MAP_FILE;
564 #endif
565   Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
566   if (Mapping == MAP_FAILED)
567     return error_code(errno, system_category());
568   return error_code::success();
569 }
570
571 mapped_file_region::mapped_file_region(const Twine &path,
572                                        mapmode mode,
573                                        uint64_t length,
574                                        uint64_t offset,
575                                        error_code &ec)
576   : Mode(mode)
577   , Size(length)
578   , Mapping() {
579   // Make sure that the requested size fits within SIZE_T.
580   if (length > std::numeric_limits<size_t>::max()) {
581     ec = make_error_code(errc::invalid_argument);
582     return;
583   }
584
585   SmallString<128> path_storage;
586   StringRef name = path.toNullTerminatedStringRef(path_storage);
587   int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
588   int ofd = ::open(name.begin(), oflags);
589   if (ofd == -1) {
590     ec = error_code(errno, system_category());
591     return;
592   }
593
594   ec = init(ofd, true, offset);
595   if (ec)
596     Mapping = 0;
597 }
598
599 mapped_file_region::mapped_file_region(int fd,
600                                        bool closefd,
601                                        mapmode mode,
602                                        uint64_t length,
603                                        uint64_t offset,
604                                        error_code &ec)
605   : Mode(mode)
606   , Size(length)
607   , Mapping() {
608   // Make sure that the requested size fits within SIZE_T.
609   if (length > std::numeric_limits<size_t>::max()) {
610     ec = make_error_code(errc::invalid_argument);
611     return;
612   }
613
614   ec = init(fd, closefd, offset);
615   if (ec)
616     Mapping = 0;
617 }
618
619 mapped_file_region::~mapped_file_region() {
620   if (Mapping)
621     ::munmap(Mapping, Size);
622 }
623
624 #if LLVM_HAS_RVALUE_REFERENCES
625 mapped_file_region::mapped_file_region(mapped_file_region &&other)
626   : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
627   other.Mapping = 0;
628 }
629 #endif
630
631 mapped_file_region::mapmode mapped_file_region::flags() const {
632   assert(Mapping && "Mapping failed but used anyway!");
633   return Mode;
634 }
635
636 uint64_t mapped_file_region::size() const {
637   assert(Mapping && "Mapping failed but used anyway!");
638   return Size;
639 }
640
641 char *mapped_file_region::data() const {
642   assert(Mapping && "Mapping failed but used anyway!");
643   assert(Mode != readonly && "Cannot get non const data for readonly mapping!");
644   return reinterpret_cast<char*>(Mapping);
645 }
646
647 const char *mapped_file_region::const_data() const {
648   assert(Mapping && "Mapping failed but used anyway!");
649   return reinterpret_cast<const char*>(Mapping);
650 }
651
652 int mapped_file_region::alignment() {
653   return process::get_self()->page_size();
654 }
655
656 error_code detail::directory_iterator_construct(detail::DirIterState &it,
657                                                 StringRef path){
658   SmallString<128> path_null(path);
659   DIR *directory = ::opendir(path_null.c_str());
660   if (directory == 0)
661     return error_code(errno, system_category());
662
663   it.IterationHandle = reinterpret_cast<intptr_t>(directory);
664   // Add something for replace_filename to replace.
665   path::append(path_null, ".");
666   it.CurrentEntry = directory_entry(path_null.str());
667   return directory_iterator_increment(it);
668 }
669
670 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
671   if (it.IterationHandle)
672     ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
673   it.IterationHandle = 0;
674   it.CurrentEntry = directory_entry();
675   return error_code::success();
676 }
677
678 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
679   errno = 0;
680   dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
681   if (cur_dir == 0 && errno != 0) {
682     return error_code(errno, system_category());
683   } else if (cur_dir != 0) {
684     StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
685     if ((name.size() == 1 && name[0] == '.') ||
686         (name.size() == 2 && name[0] == '.' && name[1] == '.'))
687       return directory_iterator_increment(it);
688     it.CurrentEntry.replace_filename(name);
689   } else
690     return directory_iterator_destruct(it);
691
692   return error_code::success();
693 }
694
695 error_code get_magic(const Twine &path, uint32_t len,
696                      SmallVectorImpl<char> &result) {
697   SmallString<128> PathStorage;
698   StringRef Path = path.toNullTerminatedStringRef(PathStorage);
699   result.set_size(0);
700
701   // Open path.
702   std::FILE *file = std::fopen(Path.data(), "rb");
703   if (file == 0)
704     return error_code(errno, system_category());
705
706   // Reserve storage.
707   result.reserve(len);
708
709   // Read magic!
710   size_t size = std::fread(result.data(), 1, len, file);
711   if (std::ferror(file) != 0) {
712     std::fclose(file);
713     return error_code(errno, system_category());
714   } else if (size != len) {
715     if (std::feof(file) != 0) {
716       std::fclose(file);
717       result.set_size(size);
718       return make_error_code(errc::value_too_large);
719     }
720   }
721   std::fclose(file);
722   result.set_size(size);
723   return error_code::success();
724 }
725
726 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,  
727                                             bool map_writable, void *&result) {
728   SmallString<128> path_storage;
729   StringRef name = path.toNullTerminatedStringRef(path_storage);
730   int oflags = map_writable ? O_RDWR : O_RDONLY;
731   int ofd = ::open(name.begin(), oflags);
732   if ( ofd == -1 )
733     return error_code(errno, system_category());
734   AutoFD fd(ofd);
735   int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
736   int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
737 #ifdef MAP_FILE
738   flags |= MAP_FILE;
739 #endif
740   result = ::mmap(0, size, prot, flags, fd, file_offset);
741   if (result == MAP_FAILED) {
742     return error_code(errno, system_category());
743   }
744   
745   return error_code::success();
746 }
747
748 error_code unmap_file_pages(void *base, size_t size) {
749   if ( ::munmap(base, size) == -1 )
750     return error_code(errno, system_category());
751    
752   return error_code::success();
753 }
754
755 error_code openFileForRead(const Twine &Name, int &ResultFD) {
756   SmallString<128> Storage;
757   StringRef P = Name.toNullTerminatedStringRef(Storage);
758   while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
759     if (errno != EINTR)
760       return error_code(errno, system_category());
761   }
762   return error_code::success();
763 }
764
765 error_code openFileForWrite(const Twine &Name, int &ResultFD,
766                             sys::fs::OpenFlags Flags, unsigned Mode) {
767   // Verify that we don't have both "append" and "excl".
768   assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
769          "Cannot specify both 'excl' and 'append' file creation flags!");
770
771   int OpenFlags = O_WRONLY | O_CREAT;
772
773   if (Flags & F_Append)
774     OpenFlags |= O_APPEND;
775   else
776     OpenFlags |= O_TRUNC;
777
778   if (Flags & F_Excl)
779     OpenFlags |= O_EXCL;
780
781   SmallString<128> Storage;
782   StringRef P = Name.toNullTerminatedStringRef(Storage);
783   while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
784     if (errno != EINTR)
785       return error_code(errno, system_category());
786   }
787   return error_code::success();
788 }
789
790 } // end namespace fs
791 } // end namespace sys
792 } // end namespace llvm