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__) || defined(__DragonFly__)
187 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
190 char fullpath[PATH_MAX];
192 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
193 if (realpath(fullpath, ret) == NULL)
195 if (stat(fullpath, &sb) != 0)
202 getprogpath(char ret[PATH_MAX], const char *bin)
206 /* First approach: absolute path. */
208 if (test_dir(ret, "/", bin) == 0)
213 /* Second approach: relative path. */
214 if (strchr(bin, '/') != NULL) {
216 if (getcwd(cwd, PATH_MAX) == NULL)
218 if (test_dir(ret, cwd, bin) == 0)
223 /* Third approach: $PATH */
224 if ((pv = getenv("PATH")) == NULL)
229 while ((t = strsep(&s, ":")) != NULL) {
230 if (test_dir(ret, t, bin) == 0) {
238 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
240 /// GetMainExecutable - Return the path to the main executable, given the
241 /// value of argv[0] from program startup.
242 std::string getMainExecutable(const char *argv0, void *MainAddr) {
243 #if defined(__APPLE__)
244 // On OS X the executable path is saved to the stack by dyld. Reading it
245 // from there is much faster than calling dladdr, especially for large
246 // binaries with symbols.
247 char exe_path[MAXPATHLEN];
248 uint32_t size = sizeof(exe_path);
249 if (_NSGetExecutablePath(exe_path, &size) == 0) {
250 char link_path[MAXPATHLEN];
251 if (realpath(exe_path, link_path))
254 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
255 defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
256 defined(__FreeBSD_kernel__)
257 char exe_path[PATH_MAX];
259 if (getprogpath(exe_path, argv0) != NULL)
261 #elif defined(__linux__) || defined(__CYGWIN__)
262 char exe_path[MAXPATHLEN];
263 StringRef aPath("/proc/self/exe");
264 if (sys::fs::exists(aPath)) {
265 // /proc is not always mounted under Linux (chroot for example).
266 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
268 return StringRef(exe_path, len);
270 // Fall back to the classical detection.
271 if (getprogpath(exe_path, argv0) != NULL)
274 #elif defined(HAVE_DLFCN_H)
275 // Use dladdr to get executable path if available.
277 int err = dladdr(MainAddr, &DLInfo);
281 // If the filename is a symlink, we need to resolve and return the location of
282 // the actual executable.
283 char link_path[MAXPATHLEN];
284 if (realpath(DLInfo.dli_fname, link_path))
287 #error GetMainExecutable is not implemented on this host yet.
292 TimeValue file_status::getLastModificationTime() const {
294 Ret.fromEpochTime(fs_st_mtime);
298 UniqueID file_status::getUniqueID() const {
299 return UniqueID(fs_st_dev, fs_st_ino);
302 error_code current_path(SmallVectorImpl<char> &result) {
305 const char *pwd = ::getenv("PWD");
306 llvm::sys::fs::file_status PWDStatus, DotStatus;
307 if (pwd && llvm::sys::path::is_absolute(pwd) &&
308 !llvm::sys::fs::status(pwd, PWDStatus) &&
309 !llvm::sys::fs::status(".", DotStatus) &&
310 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
311 result.append(pwd, pwd + strlen(pwd));
312 return error_code::success();
316 result.reserve(MAXPATHLEN);
319 result.reserve(1024);
323 if (::getcwd(result.data(), result.capacity()) == 0) {
324 // See if there was a real error.
325 if (errno != errc::not_enough_memory)
326 return error_code(errno, system_category());
327 // Otherwise there just wasn't enough space.
328 result.reserve(result.capacity() * 2);
333 result.set_size(strlen(result.data()));
334 return error_code::success();
337 error_code create_directory(const Twine &path, bool &existed) {
338 SmallString<128> path_storage;
339 StringRef p = path.toNullTerminatedStringRef(path_storage);
341 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
342 if (errno != errc::file_exists)
343 return error_code(errno, system_category());
348 return error_code::success();
351 error_code create_hard_link(const Twine &to, const Twine &from) {
353 SmallString<128> from_storage;
354 SmallString<128> to_storage;
355 StringRef f = from.toNullTerminatedStringRef(from_storage);
356 StringRef t = to.toNullTerminatedStringRef(to_storage);
358 if (::link(t.begin(), f.begin()) == -1)
359 return error_code(errno, system_category());
361 return error_code::success();
364 error_code create_symlink(const Twine &to, const Twine &from) {
366 SmallString<128> from_storage;
367 SmallString<128> to_storage;
368 StringRef f = from.toNullTerminatedStringRef(from_storage);
369 StringRef t = to.toNullTerminatedStringRef(to_storage);
371 if (::symlink(t.begin(), f.begin()) == -1)
372 return error_code(errno, system_category());
374 return error_code::success();
377 error_code remove(const Twine &path, bool &existed) {
378 SmallString<128> path_storage;
379 StringRef p = path.toNullTerminatedStringRef(path_storage);
382 if (stat(p.begin(), &buf) != 0) {
383 if (errno != errc::no_such_file_or_directory)
384 return error_code(errno, system_category());
386 return error_code::success();
389 // Note: this check catches strange situations. In all cases, LLVM should
390 // only be involved in the creation and deletion of regular files. This
391 // check ensures that what we're trying to erase is a regular file. It
392 // effectively prevents LLVM from erasing things like /dev/null, any block
393 // special file, or other things that aren't "regular" files.
394 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
395 return make_error_code(errc::operation_not_permitted);
397 if (::remove(p.begin()) == -1) {
398 if (errno != errc::no_such_file_or_directory)
399 return error_code(errno, system_category());
404 return error_code::success();
407 error_code rename(const Twine &from, const Twine &to) {
409 SmallString<128> from_storage;
410 SmallString<128> to_storage;
411 StringRef f = from.toNullTerminatedStringRef(from_storage);
412 StringRef t = to.toNullTerminatedStringRef(to_storage);
414 if (::rename(f.begin(), t.begin()) == -1)
415 return error_code(errno, system_category());
417 return error_code::success();
420 error_code resize_file(const Twine &path, uint64_t size) {
421 SmallString<128> path_storage;
422 StringRef p = path.toNullTerminatedStringRef(path_storage);
424 if (::truncate(p.begin(), size) == -1)
425 return error_code(errno, system_category());
427 return error_code::success();
430 error_code exists(const Twine &path, bool &result) {
431 SmallString<128> path_storage;
432 StringRef p = path.toNullTerminatedStringRef(path_storage);
434 if (::access(p.begin(), F_OK) == -1) {
435 if (errno != errc::no_such_file_or_directory)
436 return error_code(errno, system_category());
441 return error_code::success();
444 bool can_write(const Twine &Path) {
445 SmallString<128> PathStorage;
446 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
447 return 0 == access(P.begin(), W_OK);
450 bool can_execute(const Twine &Path) {
451 SmallString<128> PathStorage;
452 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
454 if (0 != access(P.begin(), R_OK | X_OK))
457 if (0 != stat(P.begin(), &buf))
459 if (!S_ISREG(buf.st_mode))
464 bool equivalent(file_status A, file_status B) {
465 assert(status_known(A) && status_known(B));
466 return A.fs_st_dev == B.fs_st_dev &&
467 A.fs_st_ino == B.fs_st_ino;
470 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
471 file_status fsA, fsB;
472 if (error_code ec = status(A, fsA)) return ec;
473 if (error_code ec = status(B, fsB)) return ec;
474 result = equivalent(fsA, fsB);
475 return error_code::success();
478 static error_code fillStatus(int StatRet, const struct stat &Status,
479 file_status &Result) {
481 error_code ec(errno, system_category());
482 if (ec == errc::no_such_file_or_directory)
483 Result = file_status(file_type::file_not_found);
485 Result = file_status(file_type::status_error);
489 file_type Type = file_type::type_unknown;
491 if (S_ISDIR(Status.st_mode))
492 Type = file_type::directory_file;
493 else if (S_ISREG(Status.st_mode))
494 Type = file_type::regular_file;
495 else if (S_ISBLK(Status.st_mode))
496 Type = file_type::block_file;
497 else if (S_ISCHR(Status.st_mode))
498 Type = file_type::character_file;
499 else if (S_ISFIFO(Status.st_mode))
500 Type = file_type::fifo_file;
501 else if (S_ISSOCK(Status.st_mode))
502 Type = file_type::socket_file;
504 perms Perms = static_cast<perms>(Status.st_mode);
506 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
507 Status.st_uid, Status.st_gid, Status.st_size);
509 return error_code::success();
512 error_code status(const Twine &Path, file_status &Result) {
513 SmallString<128> PathStorage;
514 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
517 int StatRet = ::stat(P.begin(), &Status);
518 return fillStatus(StatRet, Status, Result);
521 error_code status(int FD, file_status &Result) {
523 int StatRet = ::fstat(FD, &Status);
524 return fillStatus(StatRet, Status, Result);
527 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
528 #if defined(HAVE_FUTIMENS)
530 Times[0].tv_sec = Time.toPosixTime();
531 Times[0].tv_nsec = 0;
533 if (::futimens(FD, Times))
534 return error_code(errno, system_category());
535 return error_code::success();
536 #elif defined(HAVE_FUTIMES)
538 Times[0].tv_sec = Time.toPosixTime();
539 Times[0].tv_usec = 0;
541 if (::futimes(FD, Times))
542 return error_code(errno, system_category());
543 return error_code::success();
545 #warning Missing futimes() and futimens()
546 return make_error_code(errc::not_supported);
550 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
555 // Figure out how large the file is.
556 struct stat FileInfo;
557 if (fstat(FD, &FileInfo) == -1)
558 return error_code(errno, system_category());
559 uint64_t FileSize = FileInfo.st_size;
563 else if (FileSize < Size) {
564 // We need to grow the file.
565 if (ftruncate(FD, Size) == -1)
566 return error_code(errno, system_category());
569 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
570 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
574 Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
575 if (Mapping == MAP_FAILED)
576 return error_code(errno, system_category());
577 return error_code::success();
580 mapped_file_region::mapped_file_region(const Twine &path,
588 // Make sure that the requested size fits within SIZE_T.
589 if (length > std::numeric_limits<size_t>::max()) {
590 ec = make_error_code(errc::invalid_argument);
594 SmallString<128> path_storage;
595 StringRef name = path.toNullTerminatedStringRef(path_storage);
596 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
597 int ofd = ::open(name.begin(), oflags);
599 ec = error_code(errno, system_category());
603 ec = init(ofd, true, offset);
608 mapped_file_region::mapped_file_region(int fd,
617 // Make sure that the requested size fits within SIZE_T.
618 if (length > std::numeric_limits<size_t>::max()) {
619 ec = make_error_code(errc::invalid_argument);
623 ec = init(fd, closefd, offset);
628 mapped_file_region::~mapped_file_region() {
630 ::munmap(Mapping, Size);
633 #if LLVM_HAS_RVALUE_REFERENCES
634 mapped_file_region::mapped_file_region(mapped_file_region &&other)
635 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
640 mapped_file_region::mapmode mapped_file_region::flags() const {
641 assert(Mapping && "Mapping failed but used anyway!");
645 uint64_t mapped_file_region::size() const {
646 assert(Mapping && "Mapping failed but used anyway!");
650 char *mapped_file_region::data() const {
651 assert(Mapping && "Mapping failed but used anyway!");
652 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
653 return reinterpret_cast<char*>(Mapping);
656 const char *mapped_file_region::const_data() const {
657 assert(Mapping && "Mapping failed but used anyway!");
658 return reinterpret_cast<const char*>(Mapping);
661 int mapped_file_region::alignment() {
662 return process::get_self()->page_size();
665 error_code detail::directory_iterator_construct(detail::DirIterState &it,
667 SmallString<128> path_null(path);
668 DIR *directory = ::opendir(path_null.c_str());
670 return error_code(errno, system_category());
672 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
673 // Add something for replace_filename to replace.
674 path::append(path_null, ".");
675 it.CurrentEntry = directory_entry(path_null.str());
676 return directory_iterator_increment(it);
679 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
680 if (it.IterationHandle)
681 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
682 it.IterationHandle = 0;
683 it.CurrentEntry = directory_entry();
684 return error_code::success();
687 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
689 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
690 if (cur_dir == 0 && errno != 0) {
691 return error_code(errno, system_category());
692 } else if (cur_dir != 0) {
693 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
694 if ((name.size() == 1 && name[0] == '.') ||
695 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
696 return directory_iterator_increment(it);
697 it.CurrentEntry.replace_filename(name);
699 return directory_iterator_destruct(it);
701 return error_code::success();
704 error_code get_magic(const Twine &path, uint32_t len,
705 SmallVectorImpl<char> &result) {
706 SmallString<128> PathStorage;
707 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
711 std::FILE *file = std::fopen(Path.data(), "rb");
713 return error_code(errno, system_category());
719 size_t size = std::fread(result.data(), 1, len, file);
720 if (std::ferror(file) != 0) {
722 return error_code(errno, system_category());
723 } else if (size != len) {
724 if (std::feof(file) != 0) {
726 result.set_size(size);
727 return make_error_code(errc::value_too_large);
731 result.set_size(size);
732 return error_code::success();
735 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
736 bool map_writable, void *&result) {
737 SmallString<128> path_storage;
738 StringRef name = path.toNullTerminatedStringRef(path_storage);
739 int oflags = map_writable ? O_RDWR : O_RDONLY;
740 int ofd = ::open(name.begin(), oflags);
742 return error_code(errno, system_category());
744 int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
745 int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
749 result = ::mmap(0, size, prot, flags, fd, file_offset);
750 if (result == MAP_FAILED) {
751 return error_code(errno, system_category());
754 return error_code::success();
757 error_code unmap_file_pages(void *base, size_t size) {
758 if ( ::munmap(base, size) == -1 )
759 return error_code(errno, system_category());
761 return error_code::success();
764 error_code openFileForRead(const Twine &Name, int &ResultFD) {
765 SmallString<128> Storage;
766 StringRef P = Name.toNullTerminatedStringRef(Storage);
767 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
769 return error_code(errno, system_category());
771 return error_code::success();
774 error_code openFileForWrite(const Twine &Name, int &ResultFD,
775 sys::fs::OpenFlags Flags, unsigned Mode) {
776 // Verify that we don't have both "append" and "excl".
777 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
778 "Cannot specify both 'excl' and 'append' file creation flags!");
780 int OpenFlags = O_WRONLY | O_CREAT;
782 if (Flags & F_Append)
783 OpenFlags |= O_APPEND;
785 OpenFlags |= O_TRUNC;
790 SmallString<128> Storage;
791 StringRef P = Name.toNullTerminatedStringRef(Storage);
792 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
794 return error_code(errno, system_category());
796 return error_code::success();
799 } // end namespace fs
800 } // end namespace sys
801 } // end namespace llvm