1 //===- llvm/Support/Unix/PathV2.cpp - 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 PathV2 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();
116 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
117 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
118 defined(__linux__) || defined(__CYGWIN__)
120 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
121 const char *dir, const char *bin)
125 snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
126 if (realpath(buf, ret) == NULL)
128 if (stat(buf, &sb) != 0)
135 getprogpath(char ret[PATH_MAX], const char *bin)
137 char *pv, *s, *t, buf[PATH_MAX];
139 /* First approach: absolute path. */
141 if (test_dir(buf, ret, "/", bin) == 0)
146 /* Second approach: relative path. */
147 if (strchr(bin, '/') != NULL) {
148 if (getcwd(buf, PATH_MAX) == NULL)
150 if (test_dir(buf, ret, buf, bin) == 0)
155 /* Third approach: $PATH */
156 if ((pv = getenv("PATH")) == NULL)
161 while ((t = strsep(&s, ":")) != NULL) {
162 if (test_dir(buf, ret, t, bin) == 0) {
170 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
172 /// GetMainExecutable - Return the path to the main executable, given the
173 /// value of argv[0] from program startup.
174 std::string getMainExecutable(const char *argv0, void *MainAddr) {
175 #if defined(__APPLE__)
176 // On OS X the executable path is saved to the stack by dyld. Reading it
177 // from there is much faster than calling dladdr, especially for large
178 // binaries with symbols.
179 char exe_path[MAXPATHLEN];
180 uint32_t size = sizeof(exe_path);
181 if (_NSGetExecutablePath(exe_path, &size) == 0) {
182 char link_path[MAXPATHLEN];
183 if (realpath(exe_path, link_path))
186 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
187 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__)
188 char exe_path[PATH_MAX];
190 if (getprogpath(exe_path, argv0) != NULL)
192 #elif defined(__linux__) || defined(__CYGWIN__)
193 char exe_path[MAXPATHLEN];
194 StringRef aPath("/proc/self/exe");
195 if (sys::fs::exists(aPath)) {
196 // /proc is not always mounted under Linux (chroot for example).
197 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
199 return StringRef(exe_path, len);
201 // Fall back to the classical detection.
202 if (getprogpath(exe_path, argv0) != NULL)
205 #elif defined(HAVE_DLFCN_H)
206 // Use dladdr to get executable path if available.
208 int err = dladdr(MainAddr, &DLInfo);
212 // If the filename is a symlink, we need to resolve and return the location of
213 // the actual executable.
214 char link_path[MAXPATHLEN];
215 if (realpath(DLInfo.dli_fname, link_path))
218 #error GetMainExecutable is not implemented on this host yet.
223 TimeValue file_status::getLastModificationTime() const {
225 Ret.fromEpochTime(fs_st_mtime);
229 error_code current_path(SmallVectorImpl<char> &result) {
231 result.reserve(MAXPATHLEN);
234 result.reserve(1024);
238 if (::getcwd(result.data(), result.capacity()) == 0) {
239 // See if there was a real error.
240 if (errno != errc::not_enough_memory)
241 return error_code(errno, system_category());
242 // Otherwise there just wasn't enough space.
243 result.reserve(result.capacity() * 2);
248 result.set_size(strlen(result.data()));
249 return error_code::success();
252 error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
254 SmallString<128> from_storage;
255 SmallString<128> to_storage;
256 StringRef f = from.toNullTerminatedStringRef(from_storage);
257 StringRef t = to.toNullTerminatedStringRef(to_storage);
259 const size_t buf_sz = 32768;
261 int from_file = -1, to_file = -1;
264 if ((from_file = ::open(f.begin(), O_RDONLY)) < 0)
265 return error_code(errno, system_category());
266 AutoFD from_fd(from_file);
269 struct stat from_stat;
270 if (::stat(f.begin(), &from_stat) != 0)
271 return error_code(errno, system_category());
274 int to_flags = O_CREAT | O_WRONLY;
275 if (copt == copy_option::fail_if_exists)
279 if ((to_file = ::open(t.begin(), to_flags, from_stat.st_mode)) < 0)
280 return error_code(errno, system_category());
281 AutoFD to_fd(to_file);
284 ssize_t sz, sz_read = 1, sz_write;
285 while (sz_read > 0 &&
286 (sz_read = ::read(from_fd, buffer, buf_sz)) > 0) {
287 // Allow for partial writes - see Advanced Unix Programming (2nd Ed.),
288 // Marc Rochkind, Addison-Wesley, 2004, page 94
291 if ((sz = ::write(to_fd, buffer + sz_write, sz_read - sz_write)) < 0) {
292 sz_read = sz; // cause read loop termination.
296 } while (sz_write < sz_read);
299 // After all the file operations above the return value of close actually
301 if (::close(from_fd.take()) < 0) sz_read = -1;
302 if (::close(to_fd.take()) < 0) sz_read = -1;
306 return error_code(errno, system_category());
308 return error_code::success();
311 error_code create_directory(const Twine &path, bool &existed) {
312 SmallString<128> path_storage;
313 StringRef p = path.toNullTerminatedStringRef(path_storage);
315 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
316 if (errno != errc::file_exists)
317 return error_code(errno, system_category());
322 return error_code::success();
325 error_code create_hard_link(const Twine &to, const Twine &from) {
327 SmallString<128> from_storage;
328 SmallString<128> to_storage;
329 StringRef f = from.toNullTerminatedStringRef(from_storage);
330 StringRef t = to.toNullTerminatedStringRef(to_storage);
332 if (::link(t.begin(), f.begin()) == -1)
333 return error_code(errno, system_category());
335 return error_code::success();
338 error_code create_symlink(const Twine &to, const Twine &from) {
340 SmallString<128> from_storage;
341 SmallString<128> to_storage;
342 StringRef f = from.toNullTerminatedStringRef(from_storage);
343 StringRef t = to.toNullTerminatedStringRef(to_storage);
345 if (::symlink(t.begin(), f.begin()) == -1)
346 return error_code(errno, system_category());
348 return error_code::success();
351 error_code remove(const Twine &path, bool &existed) {
352 SmallString<128> path_storage;
353 StringRef p = path.toNullTerminatedStringRef(path_storage);
356 if (stat(p.begin(), &buf) != 0) {
357 if (errno != errc::no_such_file_or_directory)
358 return error_code(errno, system_category());
360 return error_code::success();
363 // Note: this check catches strange situations. In all cases, LLVM should
364 // only be involved in the creation and deletion of regular files. This
365 // check ensures that what we're trying to erase is a regular file. It
366 // effectively prevents LLVM from erasing things like /dev/null, any block
367 // special file, or other things that aren't "regular" files.
368 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
369 return make_error_code(errc::operation_not_permitted);
371 if (::remove(p.begin()) == -1) {
372 if (errno != errc::no_such_file_or_directory)
373 return error_code(errno, system_category());
378 return error_code::success();
381 error_code rename(const Twine &from, const Twine &to) {
383 SmallString<128> from_storage;
384 SmallString<128> to_storage;
385 StringRef f = from.toNullTerminatedStringRef(from_storage);
386 StringRef t = to.toNullTerminatedStringRef(to_storage);
388 if (::rename(f.begin(), t.begin()) == -1) {
389 // If it's a cross device link, copy then delete, otherwise return the error
390 if (errno == EXDEV) {
391 if (error_code ec = copy_file(from, to, copy_option::overwrite_if_exists))
394 if (error_code ec = remove(from, Existed))
397 return error_code(errno, system_category());
400 return error_code::success();
403 error_code resize_file(const Twine &path, uint64_t size) {
404 SmallString<128> path_storage;
405 StringRef p = path.toNullTerminatedStringRef(path_storage);
407 if (::truncate(p.begin(), size) == -1)
408 return error_code(errno, system_category());
410 return error_code::success();
413 error_code exists(const Twine &path, bool &result) {
414 SmallString<128> path_storage;
415 StringRef p = path.toNullTerminatedStringRef(path_storage);
417 if (::access(p.begin(), F_OK) == -1) {
418 if (errno != errc::no_such_file_or_directory)
419 return error_code(errno, system_category());
424 return error_code::success();
427 bool can_write(const Twine &Path) {
428 SmallString<128> PathStorage;
429 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
430 return 0 == access(P.begin(), W_OK);
433 bool can_execute(const Twine &Path) {
434 SmallString<128> PathStorage;
435 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
437 if (0 != access(P.begin(), R_OK | X_OK))
440 if (0 != stat(P.begin(), &buf))
442 if (!S_ISREG(buf.st_mode))
447 bool equivalent(file_status A, file_status B) {
448 assert(status_known(A) && status_known(B));
449 return A.fs_st_dev == B.fs_st_dev &&
450 A.fs_st_ino == B.fs_st_ino;
453 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
454 file_status fsA, fsB;
455 if (error_code ec = status(A, fsA)) return ec;
456 if (error_code ec = status(B, fsB)) return ec;
457 result = equivalent(fsA, fsB);
458 return error_code::success();
461 error_code file_size(const Twine &path, uint64_t &result) {
462 SmallString<128> path_storage;
463 StringRef p = path.toNullTerminatedStringRef(path_storage);
466 if (::stat(p.begin(), &status) == -1)
467 return error_code(errno, system_category());
468 if (!S_ISREG(status.st_mode))
469 return make_error_code(errc::operation_not_permitted);
471 result = status.st_size;
472 return error_code::success();
475 error_code getUniqueID(const Twine Path, uint64_t &Result) {
476 SmallString<128> Storage;
477 StringRef P = Path.toNullTerminatedStringRef(Storage);
480 if (::stat(P.begin(), &Status) != 0)
481 return error_code(errno, system_category());
483 Result = Status.st_ino;
484 return error_code::success();
487 error_code status(const Twine &path, file_status &result) {
488 SmallString<128> path_storage;
489 StringRef p = path.toNullTerminatedStringRef(path_storage);
492 if (::stat(p.begin(), &status) != 0) {
493 error_code ec(errno, system_category());
494 if (ec == errc::no_such_file_or_directory)
495 result = file_status(file_type::file_not_found);
497 result = file_status(file_type::status_error);
501 perms prms = static_cast<perms>(status.st_mode & perms_mask);
503 if (S_ISDIR(status.st_mode))
504 result = file_status(file_type::directory_file, prms);
505 else if (S_ISREG(status.st_mode))
506 result = file_status(file_type::regular_file, prms);
507 else if (S_ISBLK(status.st_mode))
508 result = file_status(file_type::block_file, prms);
509 else if (S_ISCHR(status.st_mode))
510 result = file_status(file_type::character_file, prms);
511 else if (S_ISFIFO(status.st_mode))
512 result = file_status(file_type::fifo_file, prms);
513 else if (S_ISSOCK(status.st_mode))
514 result = file_status(file_type::socket_file, prms);
516 result = file_status(file_type::type_unknown, prms);
518 result.fs_st_dev = status.st_dev;
519 result.fs_st_ino = status.st_ino;
520 result.fs_st_mtime = status.st_mtime;
521 result.fs_st_uid = status.st_uid;
522 result.fs_st_gid = status.st_gid;
524 return error_code::success();
527 // Modifies permissions on a file.
528 error_code permissions(const Twine &path, perms prms) {
529 if ((prms & add_perms) && (prms & remove_perms))
530 llvm_unreachable("add_perms and remove_perms are mutually exclusive");
532 // Get current permissions
533 // FIXME: We only need this stat for add_perms and remove_perms.
535 if (error_code ec = status(path, info)) {
539 // Set updated permissions.
540 SmallString<128> path_storage;
541 StringRef p = path.toNullTerminatedStringRef(path_storage);
543 if (prms & add_perms) {
544 permsToSet = (info.permissions() | prms) & perms_mask;
545 } else if (prms & remove_perms) {
546 permsToSet = (info.permissions() & ~prms) & perms_mask;
548 permsToSet = prms & perms_mask;
550 if (::chmod(p.begin(), static_cast<mode_t>(permsToSet))) {
551 return error_code(errno, system_category());
554 return error_code::success();
557 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
559 Times[0].tv_sec = Time.toPosixTime();
560 Times[0].tv_usec = 0;
562 if (::futimes(FD, Times))
563 return error_code(errno, system_category());
564 return error_code::success();
567 // Since this is most often used for temporary files, mode defaults to 0600.
568 error_code unique_file(const Twine &model, int &result_fd,
569 SmallVectorImpl<char> &result_path,
570 bool makeAbsolute, unsigned mode) {
571 SmallString<128> Model;
572 model.toVector(Model);
577 // Make model absolute by prepending a temp directory if it's not already.
578 bool absolute = path::is_absolute(Twine(Model));
580 SmallString<128> TDir;
581 if (error_code ec = TempDir(TDir)) return ec;
582 path::append(TDir, Twine(Model));
587 // From here on, DO NOT modify model. It may be needed if the randomly chosen
588 // path already exists.
589 SmallString<128> RandomPath = Model;
592 // Replace '%' with random chars.
593 for (unsigned i = 0, e = Model.size(); i != e; ++i) {
595 RandomPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
598 // Make sure we don't fall into an infinite loop by constantly trying
599 // to create the parent path.
600 bool TriedToCreateParent = false;
602 // Try to open + create the file.
604 int RandomFD = ::open(RandomPath.c_str(), O_RDWR | O_CREAT | O_EXCL, mode);
605 if (RandomFD == -1) {
606 int SavedErrno = errno;
607 // If the file existed, try again, otherwise, error.
608 if (SavedErrno == errc::file_exists)
609 goto retry_random_path;
610 // If path prefix doesn't exist, try to create it.
611 if (SavedErrno == errc::no_such_file_or_directory && !TriedToCreateParent) {
612 TriedToCreateParent = true;
613 StringRef p(RandomPath);
614 SmallString<64> dir_to_create;
615 for (path::const_iterator i = path::begin(p),
616 e = --path::end(p); i != e; ++i) {
617 path::append(dir_to_create, *i);
619 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
621 // Don't try to create network paths.
622 if (i->size() > 2 && (*i)[0] == '/' &&
625 return make_error_code(errc::no_such_file_or_directory);
626 if (::mkdir(dir_to_create.c_str(), 0700) == -1 &&
627 errno != errc::file_exists)
628 return error_code(errno, system_category());
631 goto rety_open_create;
634 return error_code(SavedErrno, system_category());
637 // Make the path absolute.
638 char real_path_buff[PATH_MAX + 1];
639 if (realpath(RandomPath.c_str(), real_path_buff) == NULL) {
642 ::unlink(RandomPath.c_str());
643 return error_code(error, system_category());
647 StringRef d(real_path_buff);
648 result_path.append(d.begin(), d.end());
650 result_fd = RandomFD;
651 return error_code::success();
654 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
659 // Figure out how large the file is.
660 struct stat FileInfo;
661 if (fstat(FD, &FileInfo) == -1)
662 return error_code(errno, system_category());
663 uint64_t FileSize = FileInfo.st_size;
667 else if (FileSize < Size) {
668 // We need to grow the file.
669 if (ftruncate(FD, Size) == -1)
670 return error_code(errno, system_category());
673 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
674 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
678 Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
679 if (Mapping == MAP_FAILED)
680 return error_code(errno, system_category());
681 return error_code::success();
684 mapped_file_region::mapped_file_region(const Twine &path,
692 // Make sure that the requested size fits within SIZE_T.
693 if (length > std::numeric_limits<size_t>::max()) {
694 ec = make_error_code(errc::invalid_argument);
698 SmallString<128> path_storage;
699 StringRef name = path.toNullTerminatedStringRef(path_storage);
700 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
701 int ofd = ::open(name.begin(), oflags);
703 ec = error_code(errno, system_category());
707 ec = init(ofd, true, offset);
712 mapped_file_region::mapped_file_region(int fd,
721 // Make sure that the requested size fits within SIZE_T.
722 if (length > std::numeric_limits<size_t>::max()) {
723 ec = make_error_code(errc::invalid_argument);
727 ec = init(fd, closefd, offset);
732 mapped_file_region::~mapped_file_region() {
734 ::munmap(Mapping, Size);
737 #if LLVM_HAS_RVALUE_REFERENCES
738 mapped_file_region::mapped_file_region(mapped_file_region &&other)
739 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
744 mapped_file_region::mapmode mapped_file_region::flags() const {
745 assert(Mapping && "Mapping failed but used anyway!");
749 uint64_t mapped_file_region::size() const {
750 assert(Mapping && "Mapping failed but used anyway!");
754 char *mapped_file_region::data() const {
755 assert(Mapping && "Mapping failed but used anyway!");
756 assert(Mode != readonly && "Cannot get non const data for readonly mapping!");
757 return reinterpret_cast<char*>(Mapping);
760 const char *mapped_file_region::const_data() const {
761 assert(Mapping && "Mapping failed but used anyway!");
762 return reinterpret_cast<const char*>(Mapping);
765 int mapped_file_region::alignment() {
766 return process::get_self()->page_size();
769 error_code detail::directory_iterator_construct(detail::DirIterState &it,
771 SmallString<128> path_null(path);
772 DIR *directory = ::opendir(path_null.c_str());
774 return error_code(errno, system_category());
776 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
777 // Add something for replace_filename to replace.
778 path::append(path_null, ".");
779 it.CurrentEntry = directory_entry(path_null.str());
780 return directory_iterator_increment(it);
783 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
784 if (it.IterationHandle)
785 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
786 it.IterationHandle = 0;
787 it.CurrentEntry = directory_entry();
788 return error_code::success();
791 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
793 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
794 if (cur_dir == 0 && errno != 0) {
795 return error_code(errno, system_category());
796 } else if (cur_dir != 0) {
797 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
798 if ((name.size() == 1 && name[0] == '.') ||
799 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
800 return directory_iterator_increment(it);
801 it.CurrentEntry.replace_filename(name);
803 return directory_iterator_destruct(it);
805 return error_code::success();
808 error_code get_magic(const Twine &path, uint32_t len,
809 SmallVectorImpl<char> &result) {
810 SmallString<128> PathStorage;
811 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
815 std::FILE *file = std::fopen(Path.data(), "rb");
817 return error_code(errno, system_category());
823 size_t size = std::fread(result.data(), 1, len, file);
824 if (std::ferror(file) != 0) {
826 return error_code(errno, system_category());
827 } else if (size != len) {
828 if (std::feof(file) != 0) {
830 result.set_size(size);
831 return make_error_code(errc::value_too_large);
835 result.set_size(size);
836 return error_code::success();
839 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
840 bool map_writable, void *&result) {
841 SmallString<128> path_storage;
842 StringRef name = path.toNullTerminatedStringRef(path_storage);
843 int oflags = map_writable ? O_RDWR : O_RDONLY;
844 int ofd = ::open(name.begin(), oflags);
846 return error_code(errno, system_category());
848 int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
849 int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
853 result = ::mmap(0, size, prot, flags, fd, file_offset);
854 if (result == MAP_FAILED) {
855 return error_code(errno, system_category());
858 return error_code::success();
861 error_code unmap_file_pages(void *base, size_t size) {
862 if ( ::munmap(base, size) == -1 )
863 return error_code(errno, system_category());
865 return error_code::success();
869 } // end namespace fs
870 } // end namespace sys
871 } // end namespace llvm