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;}
90 static error_code TempDir(SmallVectorImpl<char> &result) {
91 // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
93 (dir = std::getenv("TMPDIR")) || (dir = std::getenv("TMP")) ||
94 (dir = std::getenv("TEMP")) || (dir = std::getenv("TEMPDIR")) ||
102 result.append(d.begin(), d.end());
103 return error_code::success();
106 static error_code createUniqueEntity(const Twine &Model, int &ResultFD,
107 SmallVectorImpl<char> &ResultPath,
108 bool MakeAbsolute, unsigned Mode,
110 SmallString<128> ModelStorage;
111 Model.toVector(ModelStorage);
114 // Make model absolute by prepending a temp directory if it's not already.
115 bool absolute = sys::path::is_absolute(Twine(ModelStorage));
117 SmallString<128> TDir;
118 if (error_code ec = TempDir(TDir)) return ec;
119 sys::path::append(TDir, Twine(ModelStorage));
120 ModelStorage.swap(TDir);
124 // From here on, DO NOT modify model. It may be needed if the randomly chosen
125 // path already exists.
126 ResultPath = ModelStorage;
128 ResultPath.push_back(0);
129 ResultPath.pop_back();
132 // Replace '%' with random chars.
133 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
134 if (ModelStorage[i] == '%')
135 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
138 // Try to open + create the file.
141 int RandomFD = ::open(ResultPath.begin(), O_RDWR | O_CREAT | O_EXCL, Mode);
142 if (RandomFD == -1) {
143 int SavedErrno = errno;
144 // If the file existed, try again, otherwise, error.
145 if (SavedErrno == errc::file_exists)
146 goto retry_random_path;
147 return error_code(SavedErrno, system_category());
151 return error_code::success();
156 error_code EC = sys::fs::exists(ResultPath.begin(), Exists);
160 goto retry_random_path;
161 return error_code::success();
165 if (error_code EC = sys::fs::create_directory(ResultPath.begin(), false)) {
166 if (EC == errc::file_exists)
167 goto retry_random_path;
170 return error_code::success();
173 llvm_unreachable("Invalid Type");
179 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
180 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
181 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
183 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
186 char fullpath[PATH_MAX];
188 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
189 if (realpath(fullpath, ret) == NULL)
191 if (stat(fullpath, &sb) != 0)
198 getprogpath(char ret[PATH_MAX], const char *bin)
202 /* First approach: absolute path. */
204 if (test_dir(ret, "/", bin) == 0)
209 /* Second approach: relative path. */
210 if (strchr(bin, '/') != NULL) {
212 if (getcwd(cwd, PATH_MAX) == NULL)
214 if (test_dir(ret, cwd, bin) == 0)
219 /* Third approach: $PATH */
220 if ((pv = getenv("PATH")) == NULL)
225 while ((t = strsep(&s, ":")) != NULL) {
226 if (test_dir(ret, t, bin) == 0) {
234 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
236 /// GetMainExecutable - Return the path to the main executable, given the
237 /// value of argv[0] from program startup.
238 std::string getMainExecutable(const char *argv0, void *MainAddr) {
239 #if defined(__APPLE__)
240 // On OS X the executable path is saved to the stack by dyld. Reading it
241 // from there is much faster than calling dladdr, especially for large
242 // binaries with symbols.
243 char exe_path[MAXPATHLEN];
244 uint32_t size = sizeof(exe_path);
245 if (_NSGetExecutablePath(exe_path, &size) == 0) {
246 char link_path[MAXPATHLEN];
247 if (realpath(exe_path, link_path))
250 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
251 defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
252 defined(__FreeBSD_kernel__)
253 char exe_path[PATH_MAX];
255 if (getprogpath(exe_path, argv0) != NULL)
257 #elif defined(__linux__) || defined(__CYGWIN__)
258 char exe_path[MAXPATHLEN];
259 StringRef aPath("/proc/self/exe");
260 if (sys::fs::exists(aPath)) {
261 // /proc is not always mounted under Linux (chroot for example).
262 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
264 return StringRef(exe_path, len);
266 // Fall back to the classical detection.
267 if (getprogpath(exe_path, argv0) != NULL)
270 #elif defined(HAVE_DLFCN_H)
271 // Use dladdr to get executable path if available.
273 int err = dladdr(MainAddr, &DLInfo);
277 // If the filename is a symlink, we need to resolve and return the location of
278 // the actual executable.
279 char link_path[MAXPATHLEN];
280 if (realpath(DLInfo.dli_fname, link_path))
283 #error GetMainExecutable is not implemented on this host yet.
288 TimeValue file_status::getLastModificationTime() const {
290 Ret.fromEpochTime(fs_st_mtime);
294 UniqueID file_status::getUniqueID() const {
295 return UniqueID(fs_st_dev, fs_st_ino);
298 error_code current_path(SmallVectorImpl<char> &result) {
301 const char *pwd = ::getenv("PWD");
302 llvm::sys::fs::file_status PWDStatus, DotStatus;
303 if (pwd && llvm::sys::path::is_absolute(pwd) &&
304 !llvm::sys::fs::status(pwd, PWDStatus) &&
305 !llvm::sys::fs::status(".", DotStatus) &&
306 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
307 result.append(pwd, pwd + strlen(pwd));
308 return error_code::success();
312 result.reserve(MAXPATHLEN);
315 result.reserve(1024);
319 if (::getcwd(result.data(), result.capacity()) == 0) {
320 // See if there was a real error.
321 if (errno != errc::not_enough_memory)
322 return error_code(errno, system_category());
323 // Otherwise there just wasn't enough space.
324 result.reserve(result.capacity() * 2);
329 result.set_size(strlen(result.data()));
330 return error_code::success();
333 error_code create_directory(const Twine &path, bool IgnoreExisting) {
334 SmallString<128> path_storage;
335 StringRef p = path.toNullTerminatedStringRef(path_storage);
337 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
338 if (errno != errc::file_exists || !IgnoreExisting)
339 return error_code(errno, system_category());
342 return error_code::success();
345 error_code create_hard_link(const Twine &to, const Twine &from) {
347 SmallString<128> from_storage;
348 SmallString<128> to_storage;
349 StringRef f = from.toNullTerminatedStringRef(from_storage);
350 StringRef t = to.toNullTerminatedStringRef(to_storage);
352 if (::link(t.begin(), f.begin()) == -1)
353 return error_code(errno, system_category());
355 return error_code::success();
358 error_code remove(const Twine &path, bool IgnoreNonExisting) {
359 SmallString<128> path_storage;
360 StringRef p = path.toNullTerminatedStringRef(path_storage);
363 if (stat(p.begin(), &buf) != 0) {
364 if (errno != errc::no_such_file_or_directory || !IgnoreNonExisting)
365 return error_code(errno, system_category());
366 return error_code::success();
369 // Note: this check catches strange situations. In all cases, LLVM should
370 // only be involved in the creation and deletion of regular files. This
371 // check ensures that what we're trying to erase is a regular file. It
372 // effectively prevents LLVM from erasing things like /dev/null, any block
373 // special file, or other things that aren't "regular" files.
374 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
375 return make_error_code(errc::operation_not_permitted);
377 if (::remove(p.begin()) == -1) {
378 if (errno != errc::no_such_file_or_directory || !IgnoreNonExisting)
379 return error_code(errno, system_category());
382 return error_code::success();
385 error_code rename(const Twine &from, const Twine &to) {
387 SmallString<128> from_storage;
388 SmallString<128> to_storage;
389 StringRef f = from.toNullTerminatedStringRef(from_storage);
390 StringRef t = to.toNullTerminatedStringRef(to_storage);
392 if (::rename(f.begin(), t.begin()) == -1)
393 return error_code(errno, system_category());
395 return error_code::success();
398 error_code resize_file(const Twine &path, uint64_t size) {
399 SmallString<128> path_storage;
400 StringRef p = path.toNullTerminatedStringRef(path_storage);
402 if (::truncate(p.begin(), size) == -1)
403 return error_code(errno, system_category());
405 return error_code::success();
408 error_code exists(const Twine &path, bool &result) {
409 SmallString<128> path_storage;
410 StringRef p = path.toNullTerminatedStringRef(path_storage);
412 if (::access(p.begin(), F_OK) == -1) {
413 if (errno != errc::no_such_file_or_directory)
414 return error_code(errno, system_category());
419 return error_code::success();
422 bool can_write(const Twine &Path) {
423 SmallString<128> PathStorage;
424 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
425 return 0 == access(P.begin(), W_OK);
428 bool can_execute(const Twine &Path) {
429 SmallString<128> PathStorage;
430 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
432 if (0 != access(P.begin(), R_OK | X_OK))
435 if (0 != stat(P.begin(), &buf))
437 if (!S_ISREG(buf.st_mode))
442 bool equivalent(file_status A, file_status B) {
443 assert(status_known(A) && status_known(B));
444 return A.fs_st_dev == B.fs_st_dev &&
445 A.fs_st_ino == B.fs_st_ino;
448 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
449 file_status fsA, fsB;
450 if (error_code ec = status(A, fsA)) return ec;
451 if (error_code ec = status(B, fsB)) return ec;
452 result = equivalent(fsA, fsB);
453 return error_code::success();
456 static error_code fillStatus(int StatRet, const struct stat &Status,
457 file_status &Result) {
459 error_code ec(errno, system_category());
460 if (ec == errc::no_such_file_or_directory)
461 Result = file_status(file_type::file_not_found);
463 Result = file_status(file_type::status_error);
467 file_type Type = file_type::type_unknown;
469 if (S_ISDIR(Status.st_mode))
470 Type = file_type::directory_file;
471 else if (S_ISREG(Status.st_mode))
472 Type = file_type::regular_file;
473 else if (S_ISBLK(Status.st_mode))
474 Type = file_type::block_file;
475 else if (S_ISCHR(Status.st_mode))
476 Type = file_type::character_file;
477 else if (S_ISFIFO(Status.st_mode))
478 Type = file_type::fifo_file;
479 else if (S_ISSOCK(Status.st_mode))
480 Type = file_type::socket_file;
482 perms Perms = static_cast<perms>(Status.st_mode);
484 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
485 Status.st_uid, Status.st_gid, Status.st_size);
487 return error_code::success();
490 error_code status(const Twine &Path, file_status &Result) {
491 SmallString<128> PathStorage;
492 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
495 int StatRet = ::stat(P.begin(), &Status);
496 return fillStatus(StatRet, Status, Result);
499 error_code status(int FD, file_status &Result) {
501 int StatRet = ::fstat(FD, &Status);
502 return fillStatus(StatRet, Status, Result);
505 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
506 #if defined(HAVE_FUTIMENS)
508 Times[0].tv_sec = Time.toEpochTime();
509 Times[0].tv_nsec = 0;
511 if (::futimens(FD, Times))
512 return error_code(errno, system_category());
513 return error_code::success();
514 #elif defined(HAVE_FUTIMES)
516 Times[0].tv_sec = Time.toEpochTime();
517 Times[0].tv_usec = 0;
519 if (::futimes(FD, Times))
520 return error_code(errno, system_category());
521 return error_code::success();
523 #warning Missing futimes() and futimens()
524 return make_error_code(errc::not_supported);
528 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
533 // Figure out how large the file is.
534 struct stat FileInfo;
535 if (fstat(FD, &FileInfo) == -1)
536 return error_code(errno, system_category());
537 uint64_t FileSize = FileInfo.st_size;
541 else if (FileSize < Size) {
542 // We need to grow the file.
543 if (ftruncate(FD, Size) == -1)
544 return error_code(errno, system_category());
547 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
548 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
552 Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
553 if (Mapping == MAP_FAILED)
554 return error_code(errno, system_category());
555 return error_code::success();
558 mapped_file_region::mapped_file_region(const Twine &path,
566 // Make sure that the requested size fits within SIZE_T.
567 if (length > std::numeric_limits<size_t>::max()) {
568 ec = make_error_code(errc::invalid_argument);
572 SmallString<128> path_storage;
573 StringRef name = path.toNullTerminatedStringRef(path_storage);
574 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
575 int ofd = ::open(name.begin(), oflags);
577 ec = error_code(errno, system_category());
581 ec = init(ofd, true, offset);
586 mapped_file_region::mapped_file_region(int fd,
595 // Make sure that the requested size fits within SIZE_T.
596 if (length > std::numeric_limits<size_t>::max()) {
597 ec = make_error_code(errc::invalid_argument);
601 ec = init(fd, closefd, offset);
606 mapped_file_region::~mapped_file_region() {
608 ::munmap(Mapping, Size);
611 #if LLVM_HAS_RVALUE_REFERENCES
612 mapped_file_region::mapped_file_region(mapped_file_region &&other)
613 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
618 mapped_file_region::mapmode mapped_file_region::flags() const {
619 assert(Mapping && "Mapping failed but used anyway!");
623 uint64_t mapped_file_region::size() const {
624 assert(Mapping && "Mapping failed but used anyway!");
628 char *mapped_file_region::data() const {
629 assert(Mapping && "Mapping failed but used anyway!");
630 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
631 return reinterpret_cast<char*>(Mapping);
634 const char *mapped_file_region::const_data() const {
635 assert(Mapping && "Mapping failed but used anyway!");
636 return reinterpret_cast<const char*>(Mapping);
639 int mapped_file_region::alignment() {
640 return process::get_self()->page_size();
643 error_code detail::directory_iterator_construct(detail::DirIterState &it,
645 SmallString<128> path_null(path);
646 DIR *directory = ::opendir(path_null.c_str());
648 return error_code(errno, system_category());
650 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
651 // Add something for replace_filename to replace.
652 path::append(path_null, ".");
653 it.CurrentEntry = directory_entry(path_null.str());
654 return directory_iterator_increment(it);
657 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
658 if (it.IterationHandle)
659 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
660 it.IterationHandle = 0;
661 it.CurrentEntry = directory_entry();
662 return error_code::success();
665 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
667 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
668 if (cur_dir == 0 && errno != 0) {
669 return error_code(errno, system_category());
670 } else if (cur_dir != 0) {
671 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
672 if ((name.size() == 1 && name[0] == '.') ||
673 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
674 return directory_iterator_increment(it);
675 it.CurrentEntry.replace_filename(name);
677 return directory_iterator_destruct(it);
679 return error_code::success();
682 error_code get_magic(const Twine &path, uint32_t len,
683 SmallVectorImpl<char> &result) {
684 SmallString<128> PathStorage;
685 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
689 std::FILE *file = std::fopen(Path.data(), "rb");
691 return error_code(errno, system_category());
697 size_t size = std::fread(result.data(), 1, len, file);
698 if (std::ferror(file) != 0) {
700 return error_code(errno, system_category());
701 } else if (size != len) {
702 if (std::feof(file) != 0) {
704 result.set_size(size);
705 return make_error_code(errc::value_too_large);
709 result.set_size(size);
710 return error_code::success();
713 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
714 bool map_writable, void *&result) {
715 SmallString<128> path_storage;
716 StringRef name = path.toNullTerminatedStringRef(path_storage);
717 int oflags = map_writable ? O_RDWR : O_RDONLY;
718 int ofd = ::open(name.begin(), oflags);
720 return error_code(errno, system_category());
722 int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
723 int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
727 result = ::mmap(0, size, prot, flags, fd, file_offset);
728 if (result == MAP_FAILED) {
729 return error_code(errno, system_category());
732 return error_code::success();
735 error_code unmap_file_pages(void *base, size_t size) {
736 if ( ::munmap(base, size) == -1 )
737 return error_code(errno, system_category());
739 return error_code::success();
742 error_code openFileForRead(const Twine &Name, int &ResultFD) {
743 SmallString<128> Storage;
744 StringRef P = Name.toNullTerminatedStringRef(Storage);
745 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
747 return error_code(errno, system_category());
749 return error_code::success();
752 error_code openFileForWrite(const Twine &Name, int &ResultFD,
753 sys::fs::OpenFlags Flags, unsigned Mode) {
754 // Verify that we don't have both "append" and "excl".
755 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
756 "Cannot specify both 'excl' and 'append' file creation flags!");
758 int OpenFlags = O_WRONLY | O_CREAT;
760 if (Flags & F_Append)
761 OpenFlags |= O_APPEND;
763 OpenFlags |= O_TRUNC;
768 SmallString<128> Storage;
769 StringRef P = Name.toNullTerminatedStringRef(Storage);
770 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
772 return error_code(errno, system_category());
774 return error_code::success();
777 } // end namespace fs
781 bool home_directory(SmallVectorImpl<char> &result) {
782 if (char *RequestedDir = getenv("HOME")) {
784 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
791 } // end namespace path
793 } // end namespace sys
794 } // end namespace llvm