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