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"
29 #ifdef HAVE_SYS_MMAN_H
34 # define NAMLEN(dirent) strlen((dirent)->d_name)
36 # define dirent direct
37 # define NAMLEN(dirent) (dirent)->d_namlen
39 # include <sys/ndir.h>
50 #include <mach-o/dyld.h>
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
60 #if defined(__GNU__) && !defined(PATH_MAX)
61 # define PATH_MAX 4096
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.
75 AutoFD(int fd) : FileDescriptor(fd) {}
77 if (FileDescriptor >= 0)
78 ::close(FileDescriptor);
82 int ret = FileDescriptor;
87 operator int() const {return FileDescriptor;}
90 error_code TempDir(SmallVectorImpl<char> &result) {
91 // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
93 (dir = std::getenv("TMPDIR" )) ||
94 (dir = std::getenv("TMP" )) ||
95 (dir = std::getenv("TEMP" )) ||
96 (dir = std::getenv("TEMPDIR")) ||
104 result.append(d.begin(), d.end());
105 return error_code::success();
109 static error_code createUniqueEntity(const Twine &Model, int &ResultFD,
110 SmallVectorImpl<char> &ResultPath,
111 bool MakeAbsolute, unsigned Mode,
113 SmallString<128> ModelStorage;
114 Model.toVector(ModelStorage);
117 // Make model absolute by prepending a temp directory if it's not already.
118 bool absolute = sys::path::is_absolute(Twine(ModelStorage));
120 SmallString<128> TDir;
121 if (error_code ec = TempDir(TDir)) return ec;
122 sys::path::append(TDir, Twine(ModelStorage));
123 ModelStorage.swap(TDir);
127 // From here on, DO NOT modify model. It may be needed if the randomly chosen
128 // path already exists.
129 ResultPath = ModelStorage;
131 ResultPath.push_back(0);
132 ResultPath.pop_back();
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];
141 // Try to open + create the 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());
154 return error_code::success();
159 error_code EC = sys::fs::exists(ResultPath.begin(), Exists);
163 goto retry_random_path;
164 return error_code::success();
169 error_code EC = sys::fs::create_directory(ResultPath.begin(), Existed);
173 goto retry_random_path;
174 return error_code::success();
177 llvm_unreachable("Invalid Type");
183 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
184 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
185 defined(__linux__) || defined(__CYGWIN__)
187 test_dir(char buf[PATH_MAX], char ret[PATH_MAX],
188 const char *dir, const char *bin)
192 snprintf(buf, PATH_MAX, "%s/%s", dir, bin);
193 if (realpath(buf, ret) == NULL)
195 if (stat(buf, &sb) != 0)
202 getprogpath(char ret[PATH_MAX], const char *bin)
204 char *pv, *s, *t, buf[PATH_MAX];
206 /* First approach: absolute path. */
208 if (test_dir(buf, ret, "/", bin) == 0)
213 /* Second approach: relative path. */
214 if (strchr(bin, '/') != NULL) {
215 if (getcwd(buf, PATH_MAX) == NULL)
217 if (test_dir(buf, ret, buf, bin) == 0)
222 /* Third approach: $PATH */
223 if ((pv = getenv("PATH")) == NULL)
228 while ((t = strsep(&s, ":")) != NULL) {
229 if (test_dir(buf, 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(__FreeBSD_kernel__)
255 char exe_path[PATH_MAX];
257 if (getprogpath(exe_path, argv0) != NULL)
259 #elif defined(__linux__) || defined(__CYGWIN__)
260 char exe_path[MAXPATHLEN];
261 StringRef aPath("/proc/self/exe");
262 if (sys::fs::exists(aPath)) {
263 // /proc is not always mounted under Linux (chroot for example).
264 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
266 return StringRef(exe_path, len);
268 // Fall back to the classical detection.
269 if (getprogpath(exe_path, argv0) != NULL)
272 #elif defined(HAVE_DLFCN_H)
273 // Use dladdr to get executable path if available.
275 int err = dladdr(MainAddr, &DLInfo);
279 // If the filename is a symlink, we need to resolve and return the location of
280 // the actual executable.
281 char link_path[MAXPATHLEN];
282 if (realpath(DLInfo.dli_fname, link_path))
285 #error GetMainExecutable is not implemented on this host yet.
290 TimeValue file_status::getLastModificationTime() const {
292 Ret.fromEpochTime(fs_st_mtime);
296 error_code current_path(SmallVectorImpl<char> &result) {
298 result.reserve(MAXPATHLEN);
301 result.reserve(1024);
305 if (::getcwd(result.data(), result.capacity()) == 0) {
306 // See if there was a real error.
307 if (errno != errc::not_enough_memory)
308 return error_code(errno, system_category());
309 // Otherwise there just wasn't enough space.
310 result.reserve(result.capacity() * 2);
315 result.set_size(strlen(result.data()));
316 return error_code::success();
319 error_code create_directory(const Twine &path, bool &existed) {
320 SmallString<128> path_storage;
321 StringRef p = path.toNullTerminatedStringRef(path_storage);
323 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
324 if (errno != errc::file_exists)
325 return error_code(errno, system_category());
330 return error_code::success();
333 error_code create_hard_link(const Twine &to, const Twine &from) {
335 SmallString<128> from_storage;
336 SmallString<128> to_storage;
337 StringRef f = from.toNullTerminatedStringRef(from_storage);
338 StringRef t = to.toNullTerminatedStringRef(to_storage);
340 if (::link(t.begin(), f.begin()) == -1)
341 return error_code(errno, system_category());
343 return error_code::success();
346 error_code create_symlink(const Twine &to, const Twine &from) {
348 SmallString<128> from_storage;
349 SmallString<128> to_storage;
350 StringRef f = from.toNullTerminatedStringRef(from_storage);
351 StringRef t = to.toNullTerminatedStringRef(to_storage);
353 if (::symlink(t.begin(), f.begin()) == -1)
354 return error_code(errno, system_category());
356 return error_code::success();
359 error_code remove(const Twine &path, bool &existed) {
360 SmallString<128> path_storage;
361 StringRef p = path.toNullTerminatedStringRef(path_storage);
364 if (stat(p.begin(), &buf) != 0) {
365 if (errno != errc::no_such_file_or_directory)
366 return error_code(errno, system_category());
368 return error_code::success();
371 // Note: this check catches strange situations. In all cases, LLVM should
372 // only be involved in the creation and deletion of regular files. This
373 // check ensures that what we're trying to erase is a regular file. It
374 // effectively prevents LLVM from erasing things like /dev/null, any block
375 // special file, or other things that aren't "regular" files.
376 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
377 return make_error_code(errc::operation_not_permitted);
379 if (::remove(p.begin()) == -1) {
380 if (errno != errc::no_such_file_or_directory)
381 return error_code(errno, system_category());
386 return error_code::success();
389 error_code rename(const Twine &from, const Twine &to) {
391 SmallString<128> from_storage;
392 SmallString<128> to_storage;
393 StringRef f = from.toNullTerminatedStringRef(from_storage);
394 StringRef t = to.toNullTerminatedStringRef(to_storage);
396 if (::rename(f.begin(), t.begin()) == -1)
397 return error_code(errno, system_category());
399 return error_code::success();
402 error_code resize_file(const Twine &path, uint64_t size) {
403 SmallString<128> path_storage;
404 StringRef p = path.toNullTerminatedStringRef(path_storage);
406 if (::truncate(p.begin(), size) == -1)
407 return error_code(errno, system_category());
409 return error_code::success();
412 error_code exists(const Twine &path, bool &result) {
413 SmallString<128> path_storage;
414 StringRef p = path.toNullTerminatedStringRef(path_storage);
416 if (::access(p.begin(), F_OK) == -1) {
417 if (errno != errc::no_such_file_or_directory)
418 return error_code(errno, system_category());
423 return error_code::success();
426 bool can_write(const Twine &Path) {
427 SmallString<128> PathStorage;
428 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
429 return 0 == access(P.begin(), W_OK);
432 bool can_execute(const Twine &Path) {
433 SmallString<128> PathStorage;
434 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
436 if (0 != access(P.begin(), R_OK | X_OK))
439 if (0 != stat(P.begin(), &buf))
441 if (!S_ISREG(buf.st_mode))
446 bool equivalent(file_status A, file_status B) {
447 assert(status_known(A) && status_known(B));
448 return A.fs_st_dev == B.fs_st_dev &&
449 A.fs_st_ino == B.fs_st_ino;
452 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
453 file_status fsA, fsB;
454 if (error_code ec = status(A, fsA)) return ec;
455 if (error_code ec = status(B, fsB)) return ec;
456 result = equivalent(fsA, fsB);
457 return error_code::success();
460 error_code getUniqueID(const Twine Path, uint64_t &Result) {
461 SmallString<128> Storage;
462 StringRef P = Path.toNullTerminatedStringRef(Storage);
465 if (::stat(P.begin(), &Status) != 0)
466 return error_code(errno, system_category());
468 Result = Status.st_ino;
469 return error_code::success();
472 static error_code fillStatus(int StatRet, const struct stat &Status,
473 file_status &Result) {
475 error_code ec(errno, system_category());
476 if (ec == errc::no_such_file_or_directory)
477 Result = file_status(file_type::file_not_found);
479 Result = file_status(file_type::status_error);
483 file_type Type = file_type::type_unknown;
485 if (S_ISDIR(Status.st_mode))
486 Type = file_type::directory_file;
487 else if (S_ISREG(Status.st_mode))
488 Type = file_type::regular_file;
489 else if (S_ISBLK(Status.st_mode))
490 Type = file_type::block_file;
491 else if (S_ISCHR(Status.st_mode))
492 Type = file_type::character_file;
493 else if (S_ISFIFO(Status.st_mode))
494 Type = file_type::fifo_file;
495 else if (S_ISSOCK(Status.st_mode))
496 Type = file_type::socket_file;
498 perms Perms = static_cast<perms>(Status.st_mode);
500 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
501 Status.st_uid, Status.st_gid, Status.st_size);
503 return error_code::success();
506 error_code status(const Twine &Path, file_status &Result) {
507 SmallString<128> PathStorage;
508 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
511 int StatRet = ::stat(P.begin(), &Status);
512 return fillStatus(StatRet, Status, Result);
515 error_code status(int FD, file_status &Result) {
517 int StatRet = ::fstat(FD, &Status);
518 return fillStatus(StatRet, Status, Result);
521 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
522 #if defined(HAVE_FUTIMENS)
524 Times[0].tv_sec = Time.toPosixTime();
525 Times[0].tv_nsec = 0;
527 if (::futimens(FD, Times))
528 #elif defined(HAVE_FUTIMES)
530 Times[0].tv_sec = Time.toPosixTime();
531 Times[0].tv_usec = 0;
533 if (::futimes(FD, Times))
535 #error Missing futimes() and futimens()
537 return error_code(errno, system_category());
538 return error_code::success();
541 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
546 // Figure out how large the file is.
547 struct stat FileInfo;
548 if (fstat(FD, &FileInfo) == -1)
549 return error_code(errno, system_category());
550 uint64_t FileSize = FileInfo.st_size;
554 else if (FileSize < Size) {
555 // We need to grow the file.
556 if (ftruncate(FD, Size) == -1)
557 return error_code(errno, system_category());
560 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
561 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
565 Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
566 if (Mapping == MAP_FAILED)
567 return error_code(errno, system_category());
568 return error_code::success();
571 mapped_file_region::mapped_file_region(const Twine &path,
579 // Make sure that the requested size fits within SIZE_T.
580 if (length > std::numeric_limits<size_t>::max()) {
581 ec = make_error_code(errc::invalid_argument);
585 SmallString<128> path_storage;
586 StringRef name = path.toNullTerminatedStringRef(path_storage);
587 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
588 int ofd = ::open(name.begin(), oflags);
590 ec = error_code(errno, system_category());
594 ec = init(ofd, true, offset);
599 mapped_file_region::mapped_file_region(int fd,
608 // Make sure that the requested size fits within SIZE_T.
609 if (length > std::numeric_limits<size_t>::max()) {
610 ec = make_error_code(errc::invalid_argument);
614 ec = init(fd, closefd, offset);
619 mapped_file_region::~mapped_file_region() {
621 ::munmap(Mapping, Size);
624 #if LLVM_HAS_RVALUE_REFERENCES
625 mapped_file_region::mapped_file_region(mapped_file_region &&other)
626 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
631 mapped_file_region::mapmode mapped_file_region::flags() const {
632 assert(Mapping && "Mapping failed but used anyway!");
636 uint64_t mapped_file_region::size() const {
637 assert(Mapping && "Mapping failed but used anyway!");
641 char *mapped_file_region::data() const {
642 assert(Mapping && "Mapping failed but used anyway!");
643 assert(Mode != readonly && "Cannot get non const data for readonly mapping!");
644 return reinterpret_cast<char*>(Mapping);
647 const char *mapped_file_region::const_data() const {
648 assert(Mapping && "Mapping failed but used anyway!");
649 return reinterpret_cast<const char*>(Mapping);
652 int mapped_file_region::alignment() {
653 return process::get_self()->page_size();
656 error_code detail::directory_iterator_construct(detail::DirIterState &it,
658 SmallString<128> path_null(path);
659 DIR *directory = ::opendir(path_null.c_str());
661 return error_code(errno, system_category());
663 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
664 // Add something for replace_filename to replace.
665 path::append(path_null, ".");
666 it.CurrentEntry = directory_entry(path_null.str());
667 return directory_iterator_increment(it);
670 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
671 if (it.IterationHandle)
672 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
673 it.IterationHandle = 0;
674 it.CurrentEntry = directory_entry();
675 return error_code::success();
678 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
680 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
681 if (cur_dir == 0 && errno != 0) {
682 return error_code(errno, system_category());
683 } else if (cur_dir != 0) {
684 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
685 if ((name.size() == 1 && name[0] == '.') ||
686 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
687 return directory_iterator_increment(it);
688 it.CurrentEntry.replace_filename(name);
690 return directory_iterator_destruct(it);
692 return error_code::success();
695 error_code get_magic(const Twine &path, uint32_t len,
696 SmallVectorImpl<char> &result) {
697 SmallString<128> PathStorage;
698 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
702 std::FILE *file = std::fopen(Path.data(), "rb");
704 return error_code(errno, system_category());
710 size_t size = std::fread(result.data(), 1, len, file);
711 if (std::ferror(file) != 0) {
713 return error_code(errno, system_category());
714 } else if (size != len) {
715 if (std::feof(file) != 0) {
717 result.set_size(size);
718 return make_error_code(errc::value_too_large);
722 result.set_size(size);
723 return error_code::success();
726 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
727 bool map_writable, void *&result) {
728 SmallString<128> path_storage;
729 StringRef name = path.toNullTerminatedStringRef(path_storage);
730 int oflags = map_writable ? O_RDWR : O_RDONLY;
731 int ofd = ::open(name.begin(), oflags);
733 return error_code(errno, system_category());
735 int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
736 int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
740 result = ::mmap(0, size, prot, flags, fd, file_offset);
741 if (result == MAP_FAILED) {
742 return error_code(errno, system_category());
745 return error_code::success();
748 error_code unmap_file_pages(void *base, size_t size) {
749 if ( ::munmap(base, size) == -1 )
750 return error_code(errno, system_category());
752 return error_code::success();
755 error_code openFileForRead(const Twine &Name, int &ResultFD) {
756 SmallString<128> Storage;
757 StringRef P = Name.toNullTerminatedStringRef(Storage);
758 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
760 return error_code(errno, system_category());
762 return error_code::success();
765 error_code openFileForWrite(const Twine &Name, int &ResultFD,
766 sys::fs::OpenFlags Flags, unsigned Mode) {
767 // Verify that we don't have both "append" and "excl".
768 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
769 "Cannot specify both 'excl' and 'append' file creation flags!");
771 int OpenFlags = O_WRONLY | O_CREAT;
773 if (Flags & F_Append)
774 OpenFlags |= O_APPEND;
776 OpenFlags |= O_TRUNC;
781 SmallString<128> Storage;
782 StringRef P = Name.toNullTerminatedStringRef(Storage);
783 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
785 return error_code(errno, system_category());
787 return error_code::success();
790 } // end namespace fs
791 } // end namespace sys
792 } // end namespace llvm