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 //===----------------------------------------------------------------------===//
20 #include "llvm/Support/Process.h"
27 #ifdef HAVE_SYS_MMAN_H
32 # define NAMLEN(dirent) strlen((dirent)->d_name)
34 # define dirent direct
35 # define NAMLEN(dirent) (dirent)->d_namlen
37 # include <sys/ndir.h>
54 #include <mach-o/dyld.h>
57 // Both stdio.h and cstdio are included via different pathes and
58 // stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
64 #if defined(__GNU__) && !defined(PATH_MAX)
65 # define PATH_MAX 4096
71 /// This class automatically closes the given file descriptor when it goes out
72 /// of scope. You can take back explicit ownership of the file descriptor by
73 /// calling take(). The destructor does not verify that close was successful.
74 /// Therefore, never allow this class to call close on a file descriptor that
75 /// has been read from or written to.
79 AutoFD(int fd) : FileDescriptor(fd) {}
81 if (FileDescriptor >= 0)
82 ::close(FileDescriptor);
86 int ret = FileDescriptor;
91 operator int() const {return FileDescriptor;}
94 error_code TempDir(SmallVectorImpl<char> &result) {
95 // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
97 (dir = std::getenv("TMPDIR" )) ||
98 (dir = std::getenv("TMP" )) ||
99 (dir = std::getenv("TEMP" )) ||
100 (dir = std::getenv("TEMPDIR")) ||
108 result.append(d.begin(), d.end());
109 return error_code::success();
113 static error_code createUniqueEntity(const Twine &Model, int &ResultFD,
114 SmallVectorImpl<char> &ResultPath,
115 bool MakeAbsolute, unsigned Mode,
117 SmallString<128> ModelStorage;
118 Model.toVector(ModelStorage);
121 // Make model absolute by prepending a temp directory if it's not already.
122 bool absolute = sys::path::is_absolute(Twine(ModelStorage));
124 SmallString<128> TDir;
125 if (error_code ec = TempDir(TDir)) return ec;
126 sys::path::append(TDir, Twine(ModelStorage));
127 ModelStorage.swap(TDir);
131 // From here on, DO NOT modify model. It may be needed if the randomly chosen
132 // path already exists.
133 ResultPath = ModelStorage;
135 ResultPath.push_back(0);
136 ResultPath.pop_back();
139 // Replace '%' with random chars.
140 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
141 if (ModelStorage[i] == '%')
142 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
145 // Try to open + create the file.
148 int RandomFD = ::open(ResultPath.begin(), O_RDWR | O_CREAT | O_EXCL, Mode);
149 if (RandomFD == -1) {
150 int SavedErrno = errno;
151 // If the file existed, try again, otherwise, error.
152 if (SavedErrno == errc::file_exists)
153 goto retry_random_path;
154 return error_code(SavedErrno, system_category());
158 return error_code::success();
163 error_code EC = sys::fs::exists(ResultPath.begin(), Exists);
167 goto retry_random_path;
168 return error_code::success();
173 error_code EC = sys::fs::create_directory(ResultPath.begin(), Existed);
177 goto retry_random_path;
178 return error_code::success();
181 llvm_unreachable("Invalid Type");
187 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
188 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
189 defined(__linux__) || defined(__CYGWIN__)
191 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
192 const char *dir, const char *bin)
196 snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
197 if (realpath(buf, ret) == NULL)
199 if (stat(buf, &sb) != 0)
206 getprogpath(char ret[PATH_MAX], const char *bin)
208 char *pv, *s, *t, buf[PATH_MAX];
210 /* First approach: absolute path. */
212 if (test_dir(buf, ret, "/", bin) == 0)
217 /* Second approach: relative path. */
218 if (strchr(bin, '/') != NULL) {
219 if (getcwd(buf, PATH_MAX) == NULL)
221 if (test_dir(buf, ret, buf, bin) == 0)
226 /* Third approach: $PATH */
227 if ((pv = getenv("PATH")) == NULL)
232 while ((t = strsep(&s, ":")) != NULL) {
233 if (test_dir(buf, ret, t, bin) == 0) {
241 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
243 /// GetMainExecutable - Return the path to the main executable, given the
244 /// value of argv[0] from program startup.
245 std::string getMainExecutable(const char *argv0, void *MainAddr) {
246 #if defined(__APPLE__)
247 // On OS X the executable path is saved to the stack by dyld. Reading it
248 // from there is much faster than calling dladdr, especially for large
249 // binaries with symbols.
250 char exe_path[MAXPATHLEN];
251 uint32_t size = sizeof(exe_path);
252 if (_NSGetExecutablePath(exe_path, &size) == 0) {
253 char link_path[MAXPATHLEN];
254 if (realpath(exe_path, link_path))
257 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
258 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__)
259 char exe_path[PATH_MAX];
261 if (getprogpath(exe_path, argv0) != NULL)
263 #elif defined(__linux__) || defined(__CYGWIN__)
264 char exe_path[MAXPATHLEN];
265 StringRef aPath("/proc/self/exe");
266 if (sys::fs::exists(aPath)) {
267 // /proc is not always mounted under Linux (chroot for example).
268 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
270 return StringRef(exe_path, len);
272 // Fall back to the classical detection.
273 if (getprogpath(exe_path, argv0) != NULL)
276 #elif defined(HAVE_DLFCN_H)
277 // Use dladdr to get executable path if available.
279 int err = dladdr(MainAddr, &DLInfo);
283 // If the filename is a symlink, we need to resolve and return the location of
284 // the actual executable.
285 char link_path[MAXPATHLEN];
286 if (realpath(DLInfo.dli_fname, link_path))
289 #error GetMainExecutable is not implemented on this host yet.
294 TimeValue file_status::getLastModificationTime() const {
296 Ret.fromEpochTime(fs_st_mtime);
300 error_code current_path(SmallVectorImpl<char> &result) {
302 result.reserve(MAXPATHLEN);
305 result.reserve(1024);
309 if (::getcwd(result.data(), result.capacity()) == 0) {
310 // See if there was a real error.
311 if (errno != errc::not_enough_memory)
312 return error_code(errno, system_category());
313 // Otherwise there just wasn't enough space.
314 result.reserve(result.capacity() * 2);
319 result.set_size(strlen(result.data()));
320 return error_code::success();
323 error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
325 SmallString<128> from_storage;
326 SmallString<128> to_storage;
327 StringRef f = from.toNullTerminatedStringRef(from_storage);
328 StringRef t = to.toNullTerminatedStringRef(to_storage);
330 const size_t buf_sz = 32768;
332 int from_file = -1, to_file = -1;
335 if ((from_file = ::open(f.begin(), O_RDONLY)) < 0)
336 return error_code(errno, system_category());
337 AutoFD from_fd(from_file);
340 struct stat from_stat;
341 if (::stat(f.begin(), &from_stat) != 0)
342 return error_code(errno, system_category());
345 int to_flags = O_CREAT | O_WRONLY;
346 if (copt == copy_option::fail_if_exists)
350 if ((to_file = ::open(t.begin(), to_flags, from_stat.st_mode)) < 0)
351 return error_code(errno, system_category());
352 AutoFD to_fd(to_file);
355 ssize_t sz, sz_read = 1, sz_write;
356 while (sz_read > 0 &&
357 (sz_read = ::read(from_fd, buffer, buf_sz)) > 0) {
358 // Allow for partial writes - see Advanced Unix Programming (2nd Ed.),
359 // Marc Rochkind, Addison-Wesley, 2004, page 94
362 if ((sz = ::write(to_fd, buffer + sz_write, sz_read - sz_write)) < 0) {
363 sz_read = sz; // cause read loop termination.
367 } while (sz_write < sz_read);
370 // After all the file operations above the return value of close actually
372 if (::close(from_fd.take()) < 0) sz_read = -1;
373 if (::close(to_fd.take()) < 0) sz_read = -1;
377 return error_code(errno, system_category());
379 return error_code::success();
382 error_code create_directory(const Twine &path, bool &existed) {
383 SmallString<128> path_storage;
384 StringRef p = path.toNullTerminatedStringRef(path_storage);
386 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
387 if (errno != errc::file_exists)
388 return error_code(errno, system_category());
393 return error_code::success();
396 error_code create_hard_link(const Twine &to, const Twine &from) {
398 SmallString<128> from_storage;
399 SmallString<128> to_storage;
400 StringRef f = from.toNullTerminatedStringRef(from_storage);
401 StringRef t = to.toNullTerminatedStringRef(to_storage);
403 if (::link(t.begin(), f.begin()) == -1)
404 return error_code(errno, system_category());
406 return error_code::success();
409 error_code create_symlink(const Twine &to, const Twine &from) {
411 SmallString<128> from_storage;
412 SmallString<128> to_storage;
413 StringRef f = from.toNullTerminatedStringRef(from_storage);
414 StringRef t = to.toNullTerminatedStringRef(to_storage);
416 if (::symlink(t.begin(), f.begin()) == -1)
417 return error_code(errno, system_category());
419 return error_code::success();
422 error_code remove(const Twine &path, bool &existed) {
423 SmallString<128> path_storage;
424 StringRef p = path.toNullTerminatedStringRef(path_storage);
427 if (stat(p.begin(), &buf) != 0) {
428 if (errno != errc::no_such_file_or_directory)
429 return error_code(errno, system_category());
431 return error_code::success();
434 // Note: this check catches strange situations. In all cases, LLVM should
435 // only be involved in the creation and deletion of regular files. This
436 // check ensures that what we're trying to erase is a regular file. It
437 // effectively prevents LLVM from erasing things like /dev/null, any block
438 // special file, or other things that aren't "regular" files.
439 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
440 return make_error_code(errc::operation_not_permitted);
442 if (::remove(p.begin()) == -1) {
443 if (errno != errc::no_such_file_or_directory)
444 return error_code(errno, system_category());
449 return error_code::success();
452 error_code rename(const Twine &from, const Twine &to) {
454 SmallString<128> from_storage;
455 SmallString<128> to_storage;
456 StringRef f = from.toNullTerminatedStringRef(from_storage);
457 StringRef t = to.toNullTerminatedStringRef(to_storage);
459 if (::rename(f.begin(), t.begin()) == -1) {
460 // If it's a cross device link, copy then delete, otherwise return the error
461 if (errno == EXDEV) {
462 if (error_code ec = copy_file(from, to, copy_option::overwrite_if_exists))
465 if (error_code ec = remove(from, Existed))
468 return error_code(errno, system_category());
471 return error_code::success();
474 error_code resize_file(const Twine &path, uint64_t size) {
475 SmallString<128> path_storage;
476 StringRef p = path.toNullTerminatedStringRef(path_storage);
478 if (::truncate(p.begin(), size) == -1)
479 return error_code(errno, system_category());
481 return error_code::success();
484 error_code exists(const Twine &path, bool &result) {
485 SmallString<128> path_storage;
486 StringRef p = path.toNullTerminatedStringRef(path_storage);
488 if (::access(p.begin(), F_OK) == -1) {
489 if (errno != errc::no_such_file_or_directory)
490 return error_code(errno, system_category());
495 return error_code::success();
498 bool can_write(const Twine &Path) {
499 SmallString<128> PathStorage;
500 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
501 return 0 == access(P.begin(), W_OK);
504 bool can_execute(const Twine &Path) {
505 SmallString<128> PathStorage;
506 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
508 if (0 != access(P.begin(), R_OK | X_OK))
511 if (0 != stat(P.begin(), &buf))
513 if (!S_ISREG(buf.st_mode))
518 bool equivalent(file_status A, file_status B) {
519 assert(status_known(A) && status_known(B));
520 return A.fs_st_dev == B.fs_st_dev &&
521 A.fs_st_ino == B.fs_st_ino;
524 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
525 file_status fsA, fsB;
526 if (error_code ec = status(A, fsA)) return ec;
527 if (error_code ec = status(B, fsB)) return ec;
528 result = equivalent(fsA, fsB);
529 return error_code::success();
532 error_code file_size(const Twine &path, uint64_t &result) {
533 SmallString<128> path_storage;
534 StringRef p = path.toNullTerminatedStringRef(path_storage);
537 if (::stat(p.begin(), &status) == -1)
538 return error_code(errno, system_category());
539 if (!S_ISREG(status.st_mode))
540 return make_error_code(errc::operation_not_permitted);
542 result = status.st_size;
543 return error_code::success();
546 error_code getUniqueID(const Twine Path, uint64_t &Result) {
547 SmallString<128> Storage;
548 StringRef P = Path.toNullTerminatedStringRef(Storage);
551 if (::stat(P.begin(), &Status) != 0)
552 return error_code(errno, system_category());
554 Result = Status.st_ino;
555 return error_code::success();
558 error_code status(const Twine &path, file_status &result) {
559 SmallString<128> path_storage;
560 StringRef p = path.toNullTerminatedStringRef(path_storage);
563 if (::stat(p.begin(), &status) != 0) {
564 error_code ec(errno, system_category());
565 if (ec == errc::no_such_file_or_directory)
566 result = file_status(file_type::file_not_found);
568 result = file_status(file_type::status_error);
572 perms prms = static_cast<perms>(status.st_mode & perms_mask);
574 if (S_ISDIR(status.st_mode))
575 result = file_status(file_type::directory_file, prms);
576 else if (S_ISREG(status.st_mode))
577 result = file_status(file_type::regular_file, prms);
578 else if (S_ISBLK(status.st_mode))
579 result = file_status(file_type::block_file, prms);
580 else if (S_ISCHR(status.st_mode))
581 result = file_status(file_type::character_file, prms);
582 else if (S_ISFIFO(status.st_mode))
583 result = file_status(file_type::fifo_file, prms);
584 else if (S_ISSOCK(status.st_mode))
585 result = file_status(file_type::socket_file, prms);
587 result = file_status(file_type::type_unknown, prms);
589 result.fs_st_dev = status.st_dev;
590 result.fs_st_ino = status.st_ino;
591 result.fs_st_mtime = status.st_mtime;
592 result.fs_st_uid = status.st_uid;
593 result.fs_st_gid = status.st_gid;
595 return error_code::success();
598 // Modifies permissions on a file.
599 error_code permissions(const Twine &path, perms prms) {
600 if ((prms & add_perms) && (prms & remove_perms))
601 llvm_unreachable("add_perms and remove_perms are mutually exclusive");
603 // Get current permissions
604 // FIXME: We only need this stat for add_perms and remove_perms.
606 if (error_code ec = status(path, info)) {
610 // Set updated permissions.
611 SmallString<128> path_storage;
612 StringRef p = path.toNullTerminatedStringRef(path_storage);
614 if (prms & add_perms) {
615 permsToSet = (info.permissions() | prms) & perms_mask;
616 } else if (prms & remove_perms) {
617 permsToSet = (info.permissions() & ~prms) & perms_mask;
619 permsToSet = prms & perms_mask;
621 if (::chmod(p.begin(), static_cast<mode_t>(permsToSet))) {
622 return error_code(errno, system_category());
625 return error_code::success();
628 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
630 Times[0].tv_sec = Time.toPosixTime();
631 Times[0].tv_usec = 0;
633 if (::futimes(FD, Times))
634 return error_code(errno, system_category());
635 return error_code::success();
638 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
643 // Figure out how large the file is.
644 struct stat FileInfo;
645 if (fstat(FD, &FileInfo) == -1)
646 return error_code(errno, system_category());
647 uint64_t FileSize = FileInfo.st_size;
651 else if (FileSize < Size) {
652 // We need to grow the file.
653 if (ftruncate(FD, Size) == -1)
654 return error_code(errno, system_category());
657 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
658 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
662 Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
663 if (Mapping == MAP_FAILED)
664 return error_code(errno, system_category());
665 return error_code::success();
668 mapped_file_region::mapped_file_region(const Twine &path,
676 // Make sure that the requested size fits within SIZE_T.
677 if (length > std::numeric_limits<size_t>::max()) {
678 ec = make_error_code(errc::invalid_argument);
682 SmallString<128> path_storage;
683 StringRef name = path.toNullTerminatedStringRef(path_storage);
684 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
685 int ofd = ::open(name.begin(), oflags);
687 ec = error_code(errno, system_category());
691 ec = init(ofd, true, offset);
696 mapped_file_region::mapped_file_region(int fd,
705 // Make sure that the requested size fits within SIZE_T.
706 if (length > std::numeric_limits<size_t>::max()) {
707 ec = make_error_code(errc::invalid_argument);
711 ec = init(fd, closefd, offset);
716 mapped_file_region::~mapped_file_region() {
718 ::munmap(Mapping, Size);
721 #if LLVM_HAS_RVALUE_REFERENCES
722 mapped_file_region::mapped_file_region(mapped_file_region &&other)
723 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
728 mapped_file_region::mapmode mapped_file_region::flags() const {
729 assert(Mapping && "Mapping failed but used anyway!");
733 uint64_t mapped_file_region::size() const {
734 assert(Mapping && "Mapping failed but used anyway!");
738 char *mapped_file_region::data() const {
739 assert(Mapping && "Mapping failed but used anyway!");
740 assert(Mode != readonly && "Cannot get non const data for readonly mapping!");
741 return reinterpret_cast<char*>(Mapping);
744 const char *mapped_file_region::const_data() const {
745 assert(Mapping && "Mapping failed but used anyway!");
746 return reinterpret_cast<const char*>(Mapping);
749 int mapped_file_region::alignment() {
750 return process::get_self()->page_size();
753 error_code detail::directory_iterator_construct(detail::DirIterState &it,
755 SmallString<128> path_null(path);
756 DIR *directory = ::opendir(path_null.c_str());
758 return error_code(errno, system_category());
760 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
761 // Add something for replace_filename to replace.
762 path::append(path_null, ".");
763 it.CurrentEntry = directory_entry(path_null.str());
764 return directory_iterator_increment(it);
767 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
768 if (it.IterationHandle)
769 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
770 it.IterationHandle = 0;
771 it.CurrentEntry = directory_entry();
772 return error_code::success();
775 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
777 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
778 if (cur_dir == 0 && errno != 0) {
779 return error_code(errno, system_category());
780 } else if (cur_dir != 0) {
781 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
782 if ((name.size() == 1 && name[0] == '.') ||
783 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
784 return directory_iterator_increment(it);
785 it.CurrentEntry.replace_filename(name);
787 return directory_iterator_destruct(it);
789 return error_code::success();
792 error_code get_magic(const Twine &path, uint32_t len,
793 SmallVectorImpl<char> &result) {
794 SmallString<128> PathStorage;
795 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
799 std::FILE *file = std::fopen(Path.data(), "rb");
801 return error_code(errno, system_category());
807 size_t size = std::fread(result.data(), 1, len, file);
808 if (std::ferror(file) != 0) {
810 return error_code(errno, system_category());
811 } else if (size != len) {
812 if (std::feof(file) != 0) {
814 result.set_size(size);
815 return make_error_code(errc::value_too_large);
819 result.set_size(size);
820 return error_code::success();
823 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
824 bool map_writable, void *&result) {
825 SmallString<128> path_storage;
826 StringRef name = path.toNullTerminatedStringRef(path_storage);
827 int oflags = map_writable ? O_RDWR : O_RDONLY;
828 int ofd = ::open(name.begin(), oflags);
830 return error_code(errno, system_category());
832 int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
833 int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
837 result = ::mmap(0, size, prot, flags, fd, file_offset);
838 if (result == MAP_FAILED) {
839 return error_code(errno, system_category());
842 return error_code::success();
845 error_code unmap_file_pages(void *base, size_t size) {
846 if ( ::munmap(base, size) == -1 )
847 return error_code(errno, system_category());
849 return error_code::success();
853 } // end namespace fs
854 } // end namespace sys
855 } // end namespace llvm