1 //===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Unix specific implementation of the Path API.
12 //===----------------------------------------------------------------------===//
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic UNIX code that
16 //=== is guaranteed to work on *all* UNIX variants.
17 //===----------------------------------------------------------------------===//
28 #ifdef HAVE_SYS_MMAN_H
33 # define NAMLEN(dirent) strlen((dirent)->d_name)
35 # define dirent direct
36 # define NAMLEN(dirent) (dirent)->d_namlen
38 # include <sys/ndir.h>
49 #include <mach-o/dyld.h>
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
59 #if defined(__GNU__) && !defined(PATH_MAX)
60 # define PATH_MAX 4096
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.
74 AutoFD(int fd) : FileDescriptor(fd) {}
76 if (FileDescriptor >= 0)
77 ::close(FileDescriptor);
81 int ret = FileDescriptor;
86 operator int() const {return FileDescriptor;}
89 error_code TempDir(SmallVectorImpl<char> &result) {
90 // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
92 (dir = std::getenv("TMPDIR" )) ||
93 (dir = std::getenv("TMP" )) ||
94 (dir = std::getenv("TEMP" )) ||
95 (dir = std::getenv("TEMPDIR")) ||
103 result.append(d.begin(), d.end());
104 return error_code::success();
108 static error_code createUniqueEntity(const Twine &Model, int &ResultFD,
109 SmallVectorImpl<char> &ResultPath,
110 bool MakeAbsolute, unsigned Mode,
112 SmallString<128> ModelStorage;
113 Model.toVector(ModelStorage);
116 // Make model absolute by prepending a temp directory if it's not already.
117 bool absolute = sys::path::is_absolute(Twine(ModelStorage));
119 SmallString<128> TDir;
120 if (error_code ec = TempDir(TDir)) return ec;
121 sys::path::append(TDir, Twine(ModelStorage));
122 ModelStorage.swap(TDir);
126 // From here on, DO NOT modify model. It may be needed if the randomly chosen
127 // path already exists.
128 ResultPath = ModelStorage;
130 ResultPath.push_back(0);
131 ResultPath.pop_back();
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];
140 // Try to open + create the 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());
153 return error_code::success();
158 error_code EC = sys::fs::exists(ResultPath.begin(), Exists);
162 goto retry_random_path;
163 return error_code::success();
168 error_code EC = sys::fs::create_directory(ResultPath.begin(), Existed);
172 goto retry_random_path;
173 return error_code::success();
176 llvm_unreachable("Invalid Type");
182 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
183 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
184 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
186 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
189 char fullpath[PATH_MAX];
191 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
192 if (realpath(fullpath, ret) == NULL)
194 if (stat(fullpath, &sb) != 0)
201 getprogpath(char ret[PATH_MAX], const char *bin)
205 /* First approach: absolute path. */
207 if (test_dir(ret, "/", bin) == 0)
212 /* Second approach: relative path. */
213 if (strchr(bin, '/') != NULL) {
215 if (getcwd(cwd, PATH_MAX) == NULL)
217 if (test_dir(ret, cwd, bin) == 0)
222 /* Third approach: $PATH */
223 if ((pv = getenv("PATH")) == NULL)
228 while ((t = strsep(&s, ":")) != NULL) {
229 if (test_dir(ret, t, bin) == 0) {
237 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
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))
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];
258 if (getprogpath(exe_path, argv0) != NULL)
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));
267 return StringRef(exe_path, len);
269 // Fall back to the classical detection.
270 if (getprogpath(exe_path, argv0) != NULL)
273 #elif defined(HAVE_DLFCN_H)
274 // Use dladdr to get executable path if available.
276 int err = dladdr(MainAddr, &DLInfo);
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))
286 #error GetMainExecutable is not implemented on this host yet.
291 TimeValue file_status::getLastModificationTime() const {
293 Ret.fromEpochTime(fs_st_mtime);
297 UniqueID file_status::getUniqueID() const {
298 return UniqueID(fs_st_dev, fs_st_ino);
301 error_code current_path(SmallVectorImpl<char> &result) {
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();
315 result.reserve(MAXPATHLEN);
318 result.reserve(1024);
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);
332 result.set_size(strlen(result.data()));
333 return error_code::success();
336 error_code create_directory(const Twine &path, bool &existed) {
337 SmallString<128> path_storage;
338 StringRef p = path.toNullTerminatedStringRef(path_storage);
340 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
341 if (errno != errc::file_exists)
342 return error_code(errno, system_category());
347 return error_code::success();
350 error_code create_hard_link(const Twine &to, const Twine &from) {
352 SmallString<128> from_storage;
353 SmallString<128> to_storage;
354 StringRef f = from.toNullTerminatedStringRef(from_storage);
355 StringRef t = to.toNullTerminatedStringRef(to_storage);
357 if (::link(t.begin(), f.begin()) == -1)
358 return error_code(errno, system_category());
360 return error_code::success();
363 error_code create_symlink(const Twine &to, const Twine &from) {
365 SmallString<128> from_storage;
366 SmallString<128> to_storage;
367 StringRef f = from.toNullTerminatedStringRef(from_storage);
368 StringRef t = to.toNullTerminatedStringRef(to_storage);
370 if (::symlink(t.begin(), f.begin()) == -1)
371 return error_code(errno, system_category());
373 return error_code::success();
376 error_code remove(const Twine &path, bool &existed) {
377 SmallString<128> path_storage;
378 StringRef p = path.toNullTerminatedStringRef(path_storage);
381 if (stat(p.begin(), &buf) != 0) {
382 if (errno != errc::no_such_file_or_directory)
383 return error_code(errno, system_category());
385 return error_code::success();
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))
394 return make_error_code(errc::operation_not_permitted);
396 if (::remove(p.begin()) == -1) {
397 if (errno != errc::no_such_file_or_directory)
398 return error_code(errno, system_category());
403 return error_code::success();
406 error_code rename(const Twine &from, const Twine &to) {
408 SmallString<128> from_storage;
409 SmallString<128> to_storage;
410 StringRef f = from.toNullTerminatedStringRef(from_storage);
411 StringRef t = to.toNullTerminatedStringRef(to_storage);
413 if (::rename(f.begin(), t.begin()) == -1)
414 return error_code(errno, system_category());
416 return error_code::success();
419 error_code resize_file(const Twine &path, uint64_t size) {
420 SmallString<128> path_storage;
421 StringRef p = path.toNullTerminatedStringRef(path_storage);
423 if (::truncate(p.begin(), size) == -1)
424 return error_code(errno, system_category());
426 return error_code::success();
429 error_code exists(const Twine &path, bool &result) {
430 SmallString<128> path_storage;
431 StringRef p = path.toNullTerminatedStringRef(path_storage);
433 if (::access(p.begin(), F_OK) == -1) {
434 if (errno != errc::no_such_file_or_directory)
435 return error_code(errno, system_category());
440 return error_code::success();
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);
449 bool can_execute(const Twine &Path) {
450 SmallString<128> PathStorage;
451 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
453 if (0 != access(P.begin(), R_OK | X_OK))
456 if (0 != stat(P.begin(), &buf))
458 if (!S_ISREG(buf.st_mode))
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;
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();
477 static error_code fillStatus(int StatRet, const struct stat &Status,
478 file_status &Result) {
480 error_code ec(errno, system_category());
481 if (ec == errc::no_such_file_or_directory)
482 Result = file_status(file_type::file_not_found);
484 Result = file_status(file_type::status_error);
488 file_type Type = file_type::type_unknown;
490 if (S_ISDIR(Status.st_mode))
491 Type = file_type::directory_file;
492 else if (S_ISREG(Status.st_mode))
493 Type = file_type::regular_file;
494 else if (S_ISBLK(Status.st_mode))
495 Type = file_type::block_file;
496 else if (S_ISCHR(Status.st_mode))
497 Type = file_type::character_file;
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;
503 perms Perms = static_cast<perms>(Status.st_mode);
505 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
506 Status.st_uid, Status.st_gid, Status.st_size);
508 return error_code::success();
511 error_code status(const Twine &Path, file_status &Result) {
512 SmallString<128> PathStorage;
513 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
516 int StatRet = ::stat(P.begin(), &Status);
517 return fillStatus(StatRet, Status, Result);
520 error_code status(int FD, file_status &Result) {
522 int StatRet = ::fstat(FD, &Status);
523 return fillStatus(StatRet, Status, Result);
526 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
527 #if defined(HAVE_FUTIMENS)
529 Times[0].tv_sec = Time.toPosixTime();
530 Times[0].tv_nsec = 0;
532 if (::futimens(FD, Times))
533 return error_code(errno, system_category());
534 return error_code::success();
535 #elif defined(HAVE_FUTIMES)
537 Times[0].tv_sec = Time.toPosixTime();
538 Times[0].tv_usec = 0;
540 if (::futimes(FD, Times))
541 return error_code(errno, system_category());
542 return error_code::success();
544 #warning Missing futimes() and futimens()
545 return make_error_code(errc::not_supported);
549 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
554 // Figure out how large the file is.
555 struct stat FileInfo;
556 if (fstat(FD, &FileInfo) == -1)
557 return error_code(errno, system_category());
558 uint64_t FileSize = FileInfo.st_size;
562 else if (FileSize < Size) {
563 // We need to grow the file.
564 if (ftruncate(FD, Size) == -1)
565 return error_code(errno, system_category());
568 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
569 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
573 Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
574 if (Mapping == MAP_FAILED)
575 return error_code(errno, system_category());
576 return error_code::success();
579 mapped_file_region::mapped_file_region(const Twine &path,
587 // Make sure that the requested size fits within SIZE_T.
588 if (length > std::numeric_limits<size_t>::max()) {
589 ec = make_error_code(errc::invalid_argument);
593 SmallString<128> path_storage;
594 StringRef name = path.toNullTerminatedStringRef(path_storage);
595 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
596 int ofd = ::open(name.begin(), oflags);
598 ec = error_code(errno, system_category());
602 ec = init(ofd, true, offset);
607 mapped_file_region::mapped_file_region(int fd,
616 // Make sure that the requested size fits within SIZE_T.
617 if (length > std::numeric_limits<size_t>::max()) {
618 ec = make_error_code(errc::invalid_argument);
622 ec = init(fd, closefd, offset);
627 mapped_file_region::~mapped_file_region() {
629 ::munmap(Mapping, Size);
632 #if LLVM_HAS_RVALUE_REFERENCES
633 mapped_file_region::mapped_file_region(mapped_file_region &&other)
634 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
639 mapped_file_region::mapmode mapped_file_region::flags() const {
640 assert(Mapping && "Mapping failed but used anyway!");
644 uint64_t mapped_file_region::size() const {
645 assert(Mapping && "Mapping failed but used anyway!");
649 char *mapped_file_region::data() const {
650 assert(Mapping && "Mapping failed but used anyway!");
651 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
652 return reinterpret_cast<char*>(Mapping);
655 const char *mapped_file_region::const_data() const {
656 assert(Mapping && "Mapping failed but used anyway!");
657 return reinterpret_cast<const char*>(Mapping);
660 int mapped_file_region::alignment() {
661 return process::get_self()->page_size();
664 error_code detail::directory_iterator_construct(detail::DirIterState &it,
666 SmallString<128> path_null(path);
667 DIR *directory = ::opendir(path_null.c_str());
669 return error_code(errno, system_category());
671 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
672 // Add something for replace_filename to replace.
673 path::append(path_null, ".");
674 it.CurrentEntry = directory_entry(path_null.str());
675 return directory_iterator_increment(it);
678 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
679 if (it.IterationHandle)
680 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
681 it.IterationHandle = 0;
682 it.CurrentEntry = directory_entry();
683 return error_code::success();
686 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
688 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
689 if (cur_dir == 0 && errno != 0) {
690 return error_code(errno, system_category());
691 } else if (cur_dir != 0) {
692 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
693 if ((name.size() == 1 && name[0] == '.') ||
694 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
695 return directory_iterator_increment(it);
696 it.CurrentEntry.replace_filename(name);
698 return directory_iterator_destruct(it);
700 return error_code::success();
703 error_code get_magic(const Twine &path, uint32_t len,
704 SmallVectorImpl<char> &result) {
705 SmallString<128> PathStorage;
706 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
710 std::FILE *file = std::fopen(Path.data(), "rb");
712 return error_code(errno, system_category());
718 size_t size = std::fread(result.data(), 1, len, file);
719 if (std::ferror(file) != 0) {
721 return error_code(errno, system_category());
722 } else if (size != len) {
723 if (std::feof(file) != 0) {
725 result.set_size(size);
726 return make_error_code(errc::value_too_large);
730 result.set_size(size);
731 return error_code::success();
734 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
735 bool map_writable, void *&result) {
736 SmallString<128> path_storage;
737 StringRef name = path.toNullTerminatedStringRef(path_storage);
738 int oflags = map_writable ? O_RDWR : O_RDONLY;
739 int ofd = ::open(name.begin(), oflags);
741 return error_code(errno, system_category());
743 int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
744 int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
748 result = ::mmap(0, size, prot, flags, fd, file_offset);
749 if (result == MAP_FAILED) {
750 return error_code(errno, system_category());
753 return error_code::success();
756 error_code unmap_file_pages(void *base, size_t size) {
757 if ( ::munmap(base, size) == -1 )
758 return error_code(errno, system_category());
760 return error_code::success();
763 error_code openFileForRead(const Twine &Name, int &ResultFD) {
764 SmallString<128> Storage;
765 StringRef P = Name.toNullTerminatedStringRef(Storage);
766 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
768 return error_code(errno, system_category());
770 return error_code::success();
773 error_code openFileForWrite(const Twine &Name, int &ResultFD,
774 sys::fs::OpenFlags Flags, unsigned Mode) {
775 // Verify that we don't have both "append" and "excl".
776 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
777 "Cannot specify both 'excl' and 'append' file creation flags!");
779 int OpenFlags = O_WRONLY | O_CREAT;
781 if (Flags & F_Append)
782 OpenFlags |= O_APPEND;
784 OpenFlags |= O_TRUNC;
789 SmallString<128> Storage;
790 StringRef P = Name.toNullTerminatedStringRef(Storage);
791 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
793 return error_code(errno, system_category());
795 return error_code::success();
798 } // end namespace fs
802 bool home_directory(SmallVectorImpl<char> &result) {
803 if (char *RequestedDir = getenv("HOME")) {
805 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
812 } // end namespace path
814 } // end namespace sys
815 } // end namespace llvm