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
63using namespace llvm;
64
65namespace {
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
108static 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
133retry_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    bool Existed;
168    error_code EC = sys::fs::create_directory(ResultPath.begin(), Existed);
169    if (EC)
170      return EC;
171    if (Existed)
172      goto retry_random_path;
173    return error_code::success();
174  }
175  }
176  llvm_unreachable("Invalid Type");
177}
178
179namespace llvm {
180namespace sys  {
181namespace fs {
182#if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
183    defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
184    defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
185static int
186test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
187{
188  struct stat sb;
189  char fullpath[PATH_MAX];
190
191  snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
192  if (realpath(fullpath, ret) == NULL)
193    return (1);
194  if (stat(fullpath, &sb) != 0)
195    return (1);
196
197  return (0);
198}
199
200static char *
201getprogpath(char ret[PATH_MAX], const char *bin)
202{
203  char *pv, *s, *t;
204
205  /* First approach: absolute path. */
206  if (bin[0] == '/') {
207    if (test_dir(ret, "/", bin) == 0)
208      return (ret);
209    return (NULL);
210  }
211
212  /* Second approach: relative path. */
213  if (strchr(bin, '/') != NULL) {
214    char cwd[PATH_MAX];
215    if (getcwd(cwd, PATH_MAX) == NULL)
216      return (NULL);
217    if (test_dir(ret, cwd, 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(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.
241std::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(__DragonFly__) || \
255      defined(__FreeBSD_kernel__)
256  char exe_path[PATH_MAX];
257
258  if (getprogpath(exe_path, argv0) != NULL)
259    return exe_path;
260#elif defined(__linux__) || defined(__CYGWIN__)
261  char exe_path[MAXPATHLEN];
262  StringRef aPath("/proc/self/exe");
263  if (sys::fs::exists(aPath)) {
264      // /proc is not always mounted under Linux (chroot for example).
265      ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
266      if (len >= 0)
267          return StringRef(exe_path, len);
268  } else {
269      // Fall back to the classical detection.
270      if (getprogpath(exe_path, argv0) != NULL)
271          return 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 "";
279
280  // If the filename is a symlink, we need to resolve and return the location of
281  // the actual executable.
282  char link_path[MAXPATHLEN];
283  if (realpath(DLInfo.dli_fname, link_path))
284    return link_path;
285#else
286#error GetMainExecutable is not implemented on this host yet.
287#endif
288  return "";
289}
290
291TimeValue file_status::getLastModificationTime() const {
292  TimeValue Ret;
293  Ret.fromEpochTime(fs_st_mtime);
294  return Ret;
295}
296
297UniqueID file_status::getUniqueID() const {
298  return UniqueID(fs_st_dev, fs_st_ino);
299}
300
301error_code current_path(SmallVectorImpl<char> &result) {
302  result.clear();
303
304  const char *pwd = ::getenv("PWD");
305  llvm::sys::fs::file_status PWDStatus, DotStatus;
306  if (pwd && llvm::sys::path::is_absolute(pwd) &&
307      !llvm::sys::fs::status(pwd, PWDStatus) &&
308      !llvm::sys::fs::status(".", DotStatus) &&
309      PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
310    result.append(pwd, pwd + strlen(pwd));
311    return error_code::success();
312  }
313
314#ifdef MAXPATHLEN
315  result.reserve(MAXPATHLEN);
316#else
317// For GNU Hurd
318  result.reserve(1024);
319#endif
320
321  while (true) {
322    if (::getcwd(result.data(), result.capacity()) == 0) {
323      // See if there was a real error.
324      if (errno != errc::not_enough_memory)
325        return error_code(errno, system_category());
326      // Otherwise there just wasn't enough space.
327      result.reserve(result.capacity() * 2);
328    } else
329      break;
330  }
331
332  result.set_size(strlen(result.data()));
333  return error_code::success();
334}
335
336error_code create_directory(const Twine &path, bool &existed) {
337  SmallString<128> path_storage;
338  StringRef p = path.toNullTerminatedStringRef(path_storage);
339
340  if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
341    if (errno != errc::file_exists)
342      return error_code(errno, system_category());
343    existed = true;
344  } else
345    existed = false;
346
347  return error_code::success();
348}
349
350error_code create_hard_link(const Twine &to, const Twine &from) {
351  // Get arguments.
352  SmallString<128> from_storage;
353  SmallString<128> to_storage;
354  StringRef f = from.toNullTerminatedStringRef(from_storage);
355  StringRef t = to.toNullTerminatedStringRef(to_storage);
356
357  if (::link(t.begin(), f.begin()) == -1)
358    return error_code(errno, system_category());
359
360  return error_code::success();
361}
362
363error_code remove(const Twine &path, bool &existed) {
364  SmallString<128> path_storage;
365  StringRef p = path.toNullTerminatedStringRef(path_storage);
366
367  struct stat buf;
368  if (stat(p.begin(), &buf) != 0) {
369    if (errno != errc::no_such_file_or_directory)
370      return error_code(errno, system_category());
371    existed = false;
372    return error_code::success();
373  }
374
375  // Note: this check catches strange situations. In all cases, LLVM should
376  // only be involved in the creation and deletion of regular files.  This
377  // check ensures that what we're trying to erase is a regular file. It
378  // effectively prevents LLVM from erasing things like /dev/null, any block
379  // special file, or other things that aren't "regular" files.
380  if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
381    return make_error_code(errc::operation_not_permitted);
382
383  if (::remove(p.begin()) == -1) {
384    if (errno != errc::no_such_file_or_directory)
385      return error_code(errno, system_category());
386    existed = false;
387  } else
388    existed = true;
389
390  return error_code::success();
391}
392
393error_code rename(const Twine &from, const Twine &to) {
394  // Get arguments.
395  SmallString<128> from_storage;
396  SmallString<128> to_storage;
397  StringRef f = from.toNullTerminatedStringRef(from_storage);
398  StringRef t = to.toNullTerminatedStringRef(to_storage);
399
400  if (::rename(f.begin(), t.begin()) == -1)
401    return error_code(errno, system_category());
402
403  return error_code::success();
404}
405
406error_code resize_file(const Twine &path, uint64_t size) {
407  SmallString<128> path_storage;
408  StringRef p = path.toNullTerminatedStringRef(path_storage);
409
410  if (::truncate(p.begin(), size) == -1)
411    return error_code(errno, system_category());
412
413  return error_code::success();
414}
415
416error_code exists(const Twine &path, bool &result) {
417  SmallString<128> path_storage;
418  StringRef p = path.toNullTerminatedStringRef(path_storage);
419
420  if (::access(p.begin(), F_OK) == -1) {
421    if (errno != errc::no_such_file_or_directory)
422      return error_code(errno, system_category());
423    result = false;
424  } else
425    result = true;
426
427  return error_code::success();
428}
429
430bool can_write(const Twine &Path) {
431  SmallString<128> PathStorage;
432  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
433  return 0 == access(P.begin(), W_OK);
434}
435
436bool can_execute(const Twine &Path) {
437  SmallString<128> PathStorage;
438  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
439
440  if (0 != access(P.begin(), R_OK | X_OK))
441    return false;
442  struct stat buf;
443  if (0 != stat(P.begin(), &buf))
444    return false;
445  if (!S_ISREG(buf.st_mode))
446    return false;
447  return true;
448}
449
450bool equivalent(file_status A, file_status B) {
451  assert(status_known(A) && status_known(B));
452  return A.fs_st_dev == B.fs_st_dev &&
453         A.fs_st_ino == B.fs_st_ino;
454}
455
456error_code equivalent(const Twine &A, const Twine &B, bool &result) {
457  file_status fsA, fsB;
458  if (error_code ec = status(A, fsA)) return ec;
459  if (error_code ec = status(B, fsB)) return ec;
460  result = equivalent(fsA, fsB);
461  return error_code::success();
462}
463
464static error_code fillStatus(int StatRet, const struct stat &Status,
465                             file_status &Result) {
466  if (StatRet != 0) {
467    error_code ec(errno, system_category());
468    if (ec == errc::no_such_file_or_directory)
469      Result = file_status(file_type::file_not_found);
470    else
471      Result = file_status(file_type::status_error);
472    return ec;
473  }
474
475  file_type Type = file_type::type_unknown;
476
477  if (S_ISDIR(Status.st_mode))
478    Type = file_type::directory_file;
479  else if (S_ISREG(Status.st_mode))
480    Type = file_type::regular_file;
481  else if (S_ISBLK(Status.st_mode))
482    Type = file_type::block_file;
483  else if (S_ISCHR(Status.st_mode))
484    Type = file_type::character_file;
485  else if (S_ISFIFO(Status.st_mode))
486    Type = file_type::fifo_file;
487  else if (S_ISSOCK(Status.st_mode))
488    Type = file_type::socket_file;
489
490  perms Perms = static_cast<perms>(Status.st_mode);
491  Result =
492      file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
493                  Status.st_uid, Status.st_gid, Status.st_size);
494
495  return error_code::success();
496}
497
498error_code status(const Twine &Path, file_status &Result) {
499  SmallString<128> PathStorage;
500  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
501
502  struct stat Status;
503  int StatRet = ::stat(P.begin(), &Status);
504  return fillStatus(StatRet, Status, Result);
505}
506
507error_code status(int FD, file_status &Result) {
508  struct stat Status;
509  int StatRet = ::fstat(FD, &Status);
510  return fillStatus(StatRet, Status, Result);
511}
512
513error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
514#if defined(HAVE_FUTIMENS)
515  timespec Times[2];
516  Times[0].tv_sec = Time.toEpochTime();
517  Times[0].tv_nsec = 0;
518  Times[1] = Times[0];
519  if (::futimens(FD, Times))
520    return error_code(errno, system_category());
521  return error_code::success();
522#elif defined(HAVE_FUTIMES)
523  timeval Times[2];
524  Times[0].tv_sec = Time.toEpochTime();
525  Times[0].tv_usec = 0;
526  Times[1] = Times[0];
527  if (::futimes(FD, Times))
528    return error_code(errno, system_category());
529  return error_code::success();
530#else
531#warning Missing futimes() and futimens()
532  return make_error_code(errc::not_supported);
533#endif
534}
535
536error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
537  AutoFD ScopedFD(FD);
538  if (!CloseFD)
539    ScopedFD.take();
540
541  // Figure out how large the file is.
542  struct stat FileInfo;
543  if (fstat(FD, &FileInfo) == -1)
544    return error_code(errno, system_category());
545  uint64_t FileSize = FileInfo.st_size;
546
547  if (Size == 0)
548    Size = FileSize;
549  else if (FileSize < Size) {
550    // We need to grow the file.
551    if (ftruncate(FD, Size) == -1)
552      return error_code(errno, system_category());
553  }
554
555  int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
556  int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
557#ifdef MAP_FILE
558  flags |= MAP_FILE;
559#endif
560  Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
561  if (Mapping == MAP_FAILED)
562    return error_code(errno, system_category());
563  return error_code::success();
564}
565
566mapped_file_region::mapped_file_region(const Twine &path,
567                                       mapmode mode,
568                                       uint64_t length,
569                                       uint64_t offset,
570                                       error_code &ec)
571  : Mode(mode)
572  , Size(length)
573  , Mapping() {
574  // Make sure that the requested size fits within SIZE_T.
575  if (length > std::numeric_limits<size_t>::max()) {
576    ec = make_error_code(errc::invalid_argument);
577    return;
578  }
579
580  SmallString<128> path_storage;
581  StringRef name = path.toNullTerminatedStringRef(path_storage);
582  int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
583  int ofd = ::open(name.begin(), oflags);
584  if (ofd == -1) {
585    ec = error_code(errno, system_category());
586    return;
587  }
588
589  ec = init(ofd, true, offset);
590  if (ec)
591    Mapping = 0;
592}
593
594mapped_file_region::mapped_file_region(int fd,
595                                       bool closefd,
596                                       mapmode mode,
597                                       uint64_t length,
598                                       uint64_t offset,
599                                       error_code &ec)
600  : Mode(mode)
601  , Size(length)
602  , Mapping() {
603  // Make sure that the requested size fits within SIZE_T.
604  if (length > std::numeric_limits<size_t>::max()) {
605    ec = make_error_code(errc::invalid_argument);
606    return;
607  }
608
609  ec = init(fd, closefd, offset);
610  if (ec)
611    Mapping = 0;
612}
613
614mapped_file_region::~mapped_file_region() {
615  if (Mapping)
616    ::munmap(Mapping, Size);
617}
618
619#if LLVM_HAS_RVALUE_REFERENCES
620mapped_file_region::mapped_file_region(mapped_file_region &&other)
621  : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
622  other.Mapping = 0;
623}
624#endif
625
626mapped_file_region::mapmode mapped_file_region::flags() const {
627  assert(Mapping && "Mapping failed but used anyway!");
628  return Mode;
629}
630
631uint64_t mapped_file_region::size() const {
632  assert(Mapping && "Mapping failed but used anyway!");
633  return Size;
634}
635
636char *mapped_file_region::data() const {
637  assert(Mapping && "Mapping failed but used anyway!");
638  assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
639  return reinterpret_cast<char*>(Mapping);
640}
641
642const char *mapped_file_region::const_data() const {
643  assert(Mapping && "Mapping failed but used anyway!");
644  return reinterpret_cast<const char*>(Mapping);
645}
646
647int mapped_file_region::alignment() {
648  return process::get_self()->page_size();
649}
650
651error_code detail::directory_iterator_construct(detail::DirIterState &it,
652                                                StringRef path){
653  SmallString<128> path_null(path);
654  DIR *directory = ::opendir(path_null.c_str());
655  if (directory == 0)
656    return error_code(errno, system_category());
657
658  it.IterationHandle = reinterpret_cast<intptr_t>(directory);
659  // Add something for replace_filename to replace.
660  path::append(path_null, ".");
661  it.CurrentEntry = directory_entry(path_null.str());
662  return directory_iterator_increment(it);
663}
664
665error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
666  if (it.IterationHandle)
667    ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
668  it.IterationHandle = 0;
669  it.CurrentEntry = directory_entry();
670  return error_code::success();
671}
672
673error_code detail::directory_iterator_increment(detail::DirIterState &it) {
674  errno = 0;
675  dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
676  if (cur_dir == 0 && errno != 0) {
677    return error_code(errno, system_category());
678  } else if (cur_dir != 0) {
679    StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
680    if ((name.size() == 1 && name[0] == '.') ||
681        (name.size() == 2 && name[0] == '.' && name[1] == '.'))
682      return directory_iterator_increment(it);
683    it.CurrentEntry.replace_filename(name);
684  } else
685    return directory_iterator_destruct(it);
686
687  return error_code::success();
688}
689
690error_code get_magic(const Twine &path, uint32_t len,
691                     SmallVectorImpl<char> &result) {
692  SmallString<128> PathStorage;
693  StringRef Path = path.toNullTerminatedStringRef(PathStorage);
694  result.set_size(0);
695
696  // Open path.
697  std::FILE *file = std::fopen(Path.data(), "rb");
698  if (file == 0)
699    return error_code(errno, system_category());
700
701  // Reserve storage.
702  result.reserve(len);
703
704  // Read magic!
705  size_t size = std::fread(result.data(), 1, len, file);
706  if (std::ferror(file) != 0) {
707    std::fclose(file);
708    return error_code(errno, system_category());
709  } else if (size != len) {
710    if (std::feof(file) != 0) {
711      std::fclose(file);
712      result.set_size(size);
713      return make_error_code(errc::value_too_large);
714    }
715  }
716  std::fclose(file);
717  result.set_size(size);
718  return error_code::success();
719}
720
721error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
722                                            bool map_writable, void *&result) {
723  SmallString<128> path_storage;
724  StringRef name = path.toNullTerminatedStringRef(path_storage);
725  int oflags = map_writable ? O_RDWR : O_RDONLY;
726  int ofd = ::open(name.begin(), oflags);
727  if ( ofd == -1 )
728    return error_code(errno, system_category());
729  AutoFD fd(ofd);
730  int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
731  int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
732#ifdef MAP_FILE
733  flags |= MAP_FILE;
734#endif
735  result = ::mmap(0, size, prot, flags, fd, file_offset);
736  if (result == MAP_FAILED) {
737    return error_code(errno, system_category());
738  }
739
740  return error_code::success();
741}
742
743error_code unmap_file_pages(void *base, size_t size) {
744  if ( ::munmap(base, size) == -1 )
745    return error_code(errno, system_category());
746
747  return error_code::success();
748}
749
750error_code openFileForRead(const Twine &Name, int &ResultFD) {
751  SmallString<128> Storage;
752  StringRef P = Name.toNullTerminatedStringRef(Storage);
753  while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
754    if (errno != EINTR)
755      return error_code(errno, system_category());
756  }
757  return error_code::success();
758}
759
760error_code openFileForWrite(const Twine &Name, int &ResultFD,
761                            sys::fs::OpenFlags Flags, unsigned Mode) {
762  // Verify that we don't have both "append" and "excl".
763  assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
764         "Cannot specify both 'excl' and 'append' file creation flags!");
765
766  int OpenFlags = O_WRONLY | O_CREAT;
767
768  if (Flags & F_Append)
769    OpenFlags |= O_APPEND;
770  else
771    OpenFlags |= O_TRUNC;
772
773  if (Flags & F_Excl)
774    OpenFlags |= O_EXCL;
775
776  SmallString<128> Storage;
777  StringRef P = Name.toNullTerminatedStringRef(Storage);
778  while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
779    if (errno != EINTR)
780      return error_code(errno, system_category());
781  }
782  return error_code::success();
783}
784
785} // end namespace fs
786
787namespace path {
788
789bool home_directory(SmallVectorImpl<char> &result) {
790  if (char *RequestedDir = getenv("HOME")) {
791    result.clear();
792    result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
793    return true;
794  }
795
796  return false;
797}
798
799} // end namespace path
800
801} // end namespace sys
802} // end namespace llvm
803