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