LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Unix/Path.inc
Go to the documentation of this file.
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__) || defined(__DragonFly__)
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(__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 
291 TimeValue file_status::getLastModificationTime() const {
292  TimeValue Ret;
293  Ret.fromEpochTime(fs_st_mtime);
294  return Ret;
295 }
296 
297 UniqueID file_status::getUniqueID() const {
298  return UniqueID(fs_st_dev, fs_st_ino);
299 }
300 
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 
336 error_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 
350 error_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 
363 error_code create_symlink(const Twine &to, const Twine &from) {
364  // Get arguments.
365  SmallString<128> from_storage;
366  SmallString<128> to_storage;
367  StringRef f = from.toNullTerminatedStringRef(from_storage);
368  StringRef t = to.toNullTerminatedStringRef(to_storage);
369 
370  if (::symlink(t.begin(), f.begin()) == -1)
371  return error_code(errno, system_category());
372 
373  return error_code::success();
374 }
375 
376 error_code remove(const Twine &path, bool &existed) {
377  SmallString<128> path_storage;
378  StringRef p = path.toNullTerminatedStringRef(path_storage);
379 
380  struct stat buf;
381  if (stat(p.begin(), &buf) != 0) {
382  if (errno != errc::no_such_file_or_directory)
383  return error_code(errno, system_category());
384  existed = false;
385  return error_code::success();
386  }
387 
388  // Note: this check catches strange situations. In all cases, LLVM should
389  // only be involved in the creation and deletion of regular files. This
390  // check ensures that what we're trying to erase is a regular file. It
391  // effectively prevents LLVM from erasing things like /dev/null, any block
392  // special file, or other things that aren't "regular" files.
393  if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
395 
396  if (::remove(p.begin()) == -1) {
397  if (errno != errc::no_such_file_or_directory)
398  return error_code(errno, system_category());
399  existed = false;
400  } else
401  existed = true;
402 
403  return error_code::success();
404 }
405 
406 error_code rename(const Twine &from, const Twine &to) {
407  // Get arguments.
408  SmallString<128> from_storage;
409  SmallString<128> to_storage;
410  StringRef f = from.toNullTerminatedStringRef(from_storage);
411  StringRef t = to.toNullTerminatedStringRef(to_storage);
412 
413  if (::rename(f.begin(), t.begin()) == -1)
414  return error_code(errno, system_category());
415 
416  return error_code::success();
417 }
418 
419 error_code resize_file(const Twine &path, uint64_t size) {
420  SmallString<128> path_storage;
421  StringRef p = path.toNullTerminatedStringRef(path_storage);
422 
423  if (::truncate(p.begin(), size) == -1)
424  return error_code(errno, system_category());
425 
426  return error_code::success();
427 }
428 
429 error_code exists(const Twine &path, bool &result) {
430  SmallString<128> path_storage;
431  StringRef p = path.toNullTerminatedStringRef(path_storage);
432 
433  if (::access(p.begin(), F_OK) == -1) {
434  if (errno != errc::no_such_file_or_directory)
435  return error_code(errno, system_category());
436  result = false;
437  } else
438  result = true;
439 
440  return error_code::success();
441 }
442 
443 bool can_write(const Twine &Path) {
444  SmallString<128> PathStorage;
445  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
446  return 0 == access(P.begin(), W_OK);
447 }
448 
449 bool can_execute(const Twine &Path) {
450  SmallString<128> PathStorage;
451  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
452 
453  if (0 != access(P.begin(), R_OK | X_OK))
454  return false;
455  struct stat buf;
456  if (0 != stat(P.begin(), &buf))
457  return false;
458  if (!S_ISREG(buf.st_mode))
459  return false;
460  return true;
461 }
462 
463 bool equivalent(file_status A, file_status B) {
464  assert(status_known(A) && status_known(B));
465  return A.fs_st_dev == B.fs_st_dev &&
466  A.fs_st_ino == B.fs_st_ino;
467 }
468 
469 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
470  file_status fsA, fsB;
471  if (error_code ec = status(A, fsA)) return ec;
472  if (error_code ec = status(B, fsB)) return ec;
473  result = equivalent(fsA, fsB);
474  return error_code::success();
475 }
476 
477 static error_code fillStatus(int StatRet, const struct stat &Status,
478  file_status &Result) {
479  if (StatRet != 0) {
480  error_code ec(errno, system_category());
482  Result = file_status(file_type::file_not_found);
483  else
484  Result = file_status(file_type::status_error);
485  return ec;
486  }
487 
488  file_type Type = file_type::type_unknown;
489 
490  if (S_ISDIR(Status.st_mode))
492  else if (S_ISREG(Status.st_mode))
494  else if (S_ISBLK(Status.st_mode))
495  Type = file_type::block_file;
496  else if (S_ISCHR(Status.st_mode))
498  else if (S_ISFIFO(Status.st_mode))
499  Type = file_type::fifo_file;
500  else if (S_ISSOCK(Status.st_mode))
501  Type = file_type::socket_file;
502 
503  perms Perms = static_cast<perms>(Status.st_mode);
504  Result =
505  file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
506  Status.st_uid, Status.st_gid, Status.st_size);
507 
508  return error_code::success();
509 }
510 
511 error_code status(const Twine &Path, file_status &Result) {
512  SmallString<128> PathStorage;
513  StringRef P = Path.toNullTerminatedStringRef(PathStorage);
514 
515  struct stat Status;
516  int StatRet = ::stat(P.begin(), &Status);
517  return fillStatus(StatRet, Status, Result);
518 }
519 
520 error_code status(int FD, file_status &Result) {
521  struct stat Status;
522  int StatRet = ::fstat(FD, &Status);
523  return fillStatus(StatRet, Status, Result);
524 }
525 
526 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
527 #if defined(HAVE_FUTIMENS)
528  timespec Times[2];
529  Times[0].tv_sec = Time.toPosixTime();
530  Times[0].tv_nsec = 0;
531  Times[1] = Times[0];
532  if (::futimens(FD, Times))
533 #elif defined(HAVE_FUTIMES)
534  timeval Times[2];
535  Times[0].tv_sec = Time.toPosixTime();
536  Times[0].tv_usec = 0;
537  Times[1] = Times[0];
538  if (::futimes(FD, Times))
539 #else
540 #error Missing futimes() and futimens()
541 #endif
542  return error_code(errno, system_category());
543  return error_code::success();
544 }
545 
546 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
547  AutoFD ScopedFD(FD);
548  if (!CloseFD)
549  ScopedFD.take();
550 
551  // Figure out how large the file is.
552  struct stat FileInfo;
553  if (fstat(FD, &FileInfo) == -1)
554  return error_code(errno, system_category());
555  uint64_t FileSize = FileInfo.st_size;
556 
557  if (Size == 0)
558  Size = FileSize;
559  else if (FileSize < Size) {
560  // We need to grow the file.
561  if (ftruncate(FD, Size) == -1)
562  return error_code(errno, system_category());
563  }
564 
565 #if !defined(__minix)
566  int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
567 #else
568  int flags = MAP_PRIVATE;
569 #endif /* ! defined(__minix) */
570  int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
571 #ifdef MAP_FILE
572  flags |= MAP_FILE;
573 #endif
574  Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
575  if (Mapping == MAP_FAILED)
576  return error_code(errno, system_category());
577  return error_code::success();
578 }
579 
580 mapped_file_region::mapped_file_region(const Twine &path,
581  mapmode mode,
582  uint64_t length,
583  uint64_t offset,
584  error_code &ec)
585  : Mode(mode)
586  , Size(length)
587  , Mapping() {
588  // Make sure that the requested size fits within SIZE_T.
589  if (length > std::numeric_limits<size_t>::max()) {
591  return;
592  }
593 
594  SmallString<128> path_storage;
595  StringRef name = path.toNullTerminatedStringRef(path_storage);
596  int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
597  int ofd = ::open(name.begin(), oflags);
598  if (ofd == -1) {
599  ec = error_code(errno, system_category());
600  return;
601  }
602 
603  ec = init(ofd, true, offset);
604  if (ec)
605  Mapping = 0;
606 }
607 
608 mapped_file_region::mapped_file_region(int fd,
609  bool closefd,
610  mapmode mode,
611  uint64_t length,
612  uint64_t offset,
613  error_code &ec)
614  : Mode(mode)
615  , Size(length)
616  , Mapping() {
617  // Make sure that the requested size fits within SIZE_T.
618  if (length > std::numeric_limits<size_t>::max()) {
620  return;
621  }
622 
623  ec = init(fd, closefd, offset);
624  if (ec)
625  Mapping = 0;
626 }
627 
628 mapped_file_region::~mapped_file_region() {
629  if (Mapping)
630  ::munmap(Mapping, Size);
631 }
632 
633 #if LLVM_HAS_RVALUE_REFERENCES
634 mapped_file_region::mapped_file_region(mapped_file_region &&other)
635  : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
636  other.Mapping = 0;
637 }
638 #endif
639 
640 mapped_file_region::mapmode mapped_file_region::flags() const {
641  assert(Mapping && "Mapping failed but used anyway!");
642  return Mode;
643 }
644 
645 uint64_t mapped_file_region::size() const {
646  assert(Mapping && "Mapping failed but used anyway!");
647  return Size;
648 }
649 
650 char *mapped_file_region::data() const {
651  assert(Mapping && "Mapping failed but used anyway!");
652  assert(Mode != readonly && "Cannot get non const data for readonly mapping!");
653  return reinterpret_cast<char*>(Mapping);
654 }
655 
656 const char *mapped_file_region::const_data() const {
657  assert(Mapping && "Mapping failed but used anyway!");
658  return reinterpret_cast<const char*>(Mapping);
659 }
660 
661 int mapped_file_region::alignment() {
662  return process::get_self()->page_size();
663 }
664 
665 error_code detail::directory_iterator_construct(detail::DirIterState &it,
666  StringRef path){
667  SmallString<128> path_null(path);
668  DIR *directory = ::opendir(path_null.c_str());
669  if (directory == 0)
670  return error_code(errno, system_category());
671 
672  it.IterationHandle = reinterpret_cast<intptr_t>(directory);
673  // Add something for replace_filename to replace.
674  path::append(path_null, ".");
675  it.CurrentEntry = directory_entry(path_null.str());
676  return directory_iterator_increment(it);
677 }
678 
679 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
680  if (it.IterationHandle)
681  ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
682  it.IterationHandle = 0;
683  it.CurrentEntry = directory_entry();
684  return error_code::success();
685 }
686 
687 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
688  errno = 0;
689  dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
690  if (cur_dir == 0 && errno != 0) {
691  return error_code(errno, system_category());
692  } else if (cur_dir != 0) {
693  StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
694  if ((name.size() == 1 && name[0] == '.') ||
695  (name.size() == 2 && name[0] == '.' && name[1] == '.'))
696  return directory_iterator_increment(it);
697  it.CurrentEntry.replace_filename(name);
698  } else
699  return directory_iterator_destruct(it);
700 
701  return error_code::success();
702 }
703 
704 error_code get_magic(const Twine &path, uint32_t len,
705  SmallVectorImpl<char> &result) {
706  SmallString<128> PathStorage;
707  StringRef Path = path.toNullTerminatedStringRef(PathStorage);
708  result.set_size(0);
709 
710  // Open path.
711  std::FILE *file = std::fopen(Path.data(), "rb");
712  if (file == 0)
713  return error_code(errno, system_category());
714 
715  // Reserve storage.
716  result.reserve(len);
717 
718  // Read magic!
719  size_t size = std::fread(result.data(), 1, len, file);
720  if (std::ferror(file) != 0) {
721  std::fclose(file);
722  return error_code(errno, system_category());
723  } else if (size != len) {
724  if (std::feof(file) != 0) {
725  std::fclose(file);
726  result.set_size(size);
728  }
729  }
730  std::fclose(file);
731  result.set_size(size);
732  return error_code::success();
733 }
734 
735 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
736  bool map_writable, void *&result) {
737  SmallString<128> path_storage;
738  StringRef name = path.toNullTerminatedStringRef(path_storage);
739  int oflags = map_writable ? O_RDWR : O_RDONLY;
740  int ofd = ::open(name.begin(), oflags);
741  if ( ofd == -1 )
742  return error_code(errno, system_category());
743  AutoFD fd(ofd);
744 #if !defined(__minix)
745  int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
746 #else
747  int flags = MAP_PRIVATE;
748 #endif /* !defined(__minix) */
749  int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
750 #ifdef MAP_FILE
751  flags |= MAP_FILE;
752 #endif
753  result = ::mmap(0, size, prot, flags, fd, file_offset);
754  if (result == MAP_FAILED) {
755  return error_code(errno, system_category());
756  }
757 
758  return error_code::success();
759 }
760 
761 error_code unmap_file_pages(void *base, size_t size) {
762  if ( ::munmap(base, size) == -1 )
763  return error_code(errno, system_category());
764 
765  return error_code::success();
766 }
767 
768 error_code openFileForRead(const Twine &Name, int &ResultFD) {
769  SmallString<128> Storage;
770  StringRef P = Name.toNullTerminatedStringRef(Storage);
771  while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
772  if (errno != EINTR)
773  return error_code(errno, system_category());
774  }
775  return error_code::success();
776 }
777 
778 error_code openFileForWrite(const Twine &Name, int &ResultFD,
779  sys::fs::OpenFlags Flags, unsigned Mode) {
780  // Verify that we don't have both "append" and "excl".
781  assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
782  "Cannot specify both 'excl' and 'append' file creation flags!");
783 
784  int OpenFlags = O_WRONLY | O_CREAT;
785 
786  if (Flags & F_Append)
787  OpenFlags |= O_APPEND;
788  else
789  OpenFlags |= O_TRUNC;
790 
791  if (Flags & F_Excl)
792  OpenFlags |= O_EXCL;
793 
794  SmallString<128> Storage;
795  StringRef P = Name.toNullTerminatedStringRef(Storage);
796  while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
797  if (errno != EINTR)
798  return error_code(errno, system_category());
799  }
800  return error_code::success();
801 }
802 
803 } // end namespace fs
804 } // end namespace sys
805 } // end namespace llvm
void toVector(SmallVectorImpl< char > &Out) const
Definition: Twine.cpp:26
void set_size(unsigned N)
Definition: SmallVector.h:702
void push_back(const T &Elt)
Definition: SmallVector.h:236
bool can_execute(const Twine &Path)
Can we execute this file?
size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream);
void reserve(unsigned N)
Definition: SmallVector.h:425
const error_category & system_category()
size_t size() const
size - Get the string size.
Definition: StringRef.h:113
error_code directory_iterator_construct(DirIterState &, StringRef)
int fstat(int fildes, struct stat *buf);
error_code openFileForWrite(const Twine &Name, int &ResultFD, OpenFlags Flags, unsigned Mode=0666)
error_code resize_file(const Twine &path, uint64_t size)
Resize path to size. File is resized as if by POSIX truncate().
int open(const char *path, int oflag, ... );
error_code setLastModificationAndAccessTime(int FD, TimeValue Time)
DIR *opendir(const char *dirname);.
UniqueID getUniqueID() const
error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
error_code unmap_file_pages(void *base, size_t size)
Memory unmaps the contents of a file.
error_code openFileForRead(const Twine &Name, int &ResultFD)
FILE *fopen(const char *filename, const char *mode);.
Definition: Path.cpp:158
int fclose(FILE *stream);
bool status_known(file_status s)
Is status available?
Definition: Path.cpp:772
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:372
int access(const char *path, int amode);
#define llvm_unreachable(msg)
int feof(FILE *stream);
int closedir(DIR *dirp);
bool is_absolute(const Twine &path)
Is path absolute?
Definition: Path.cpp:614
char *strchr(const char *s, int c);
May access map via data and modify it. Written to path.
Definition: FileSystem.h:687
error_code directory_iterator_destruct(DirIterState &)
error_code map_file_pages(const Twine &path, off_t file_offset, size_t size, bool map_writable, void *&result)
Memory maps the contents of a file.
bool can_write(const Twine &Path)
Can we write this file?
error_code directory_iterator_increment(DirIterState &)
ssize_t readlink(const char *path, char *buf, size_t bufsize);
May only access map via const_data as read only.
Definition: FileSystem.h:686
const char * data() const
Definition: StringRef.h:107
error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to.
iterator begin() const
Definition: StringRef.h:97
std::string getMainExecutable(const char *argv0, void *MainExecAddr)
static llvm::error_code createUniqueEntity(const llvm::Twine &Model, int &ResultFD, llvm::SmallVectorImpl< char > &ResultPath, bool MakeAbsolute, unsigned Mode, FSEntity Type)
#define P(N)
char *realpath(const char *file_name, char *resolved_name);
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:314
error_code status(const Twine &path, file_status &result)
Get file status as if by POSIX stat().
void swap(SmallVectorImpl &RHS)
Definition: SmallVector.h:710
void free(void *ptr);
int snprintf(char *s, size_t n, const char *format, ...);
int mkdir(const char *path, mode_t mode);
void append(in_iter in_start, in_iter in_end)
Definition: SmallVector.h:445
int stat(const char *path, struct stat *buf);
char *strdup(const char *s1);
static self_process * get_self()
Get the process object for the current process.
Definition: Process.cpp:29
size_t strlen(const char *s);
static unsigned GetRandomNumber()
int ferror(FILE *stream);
pointer data()
data - Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:135
error_code create_directory(const Twine &path, bool &existed)
Create the directory in path.
error_code create_symlink(const Twine &to, const Twine &from)
Create a symbolic link from from to to.
static error_code success()
Definition: system_error.h:732
size_t page_size() const
Get the virtual memory page size.
Definition: Process.h:124
bool equivalent(file_status A, file_status B)
Do file_status's represent the same thing?
StringRef toNullTerminatedStringRef(SmallVectorImpl< char > &Out) const
Definition: Twine.cpp:38
TimeValue getLastModificationTime() const
error_code rename(const Twine &from, const Twine &to)
Rename from to to. Files are renamed as if by POSIX rename().
bool exists(file_status status)
Does file exist?
Definition: Path.cpp:768
char *getenv(const char *name);
error_code get_magic(const Twine &path, uint32_t len, SmallVectorImpl< char > &result)
Get path's first len bytes.
error_code make_error_code(errc _e)
Definition: system_error.h:782
FSEntity
Definition: Path.cpp:157