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;}
89 error_code TempDir(SmallVectorImpl<char> &result) {
90 // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
92 (dir = std::getenv("TMPDIR" )) ||
93 (dir = std::getenv("TMP" )) ||
94 (dir = std::getenv("TEMP" )) ||
95 (dir = std::getenv("TEMPDIR")) ||
103 result.append(d.begin(), d.end());
104 return error_code::success();
108 static error_code createUniqueEntity(const Twine &Model, int &ResultFD,
109 SmallVectorImpl<char> &ResultPath,
110 bool MakeAbsolute, unsigned Mode,
112 SmallString<128> ModelStorage;
113 Model.toVector(ModelStorage);
116 // Make model absolute by prepending a temp directory if it's not already.
117 bool absolute = sys::path::is_absolute(Twine(ModelStorage));
119 SmallString<128> TDir;
120 if (error_code ec = TempDir(TDir)) return ec;
121 sys::path::append(TDir, Twine(ModelStorage));
122 ModelStorage.swap(TDir);
126 // From here on, DO NOT modify model. It may be needed if the randomly chosen
127 // path already exists.
128 ResultPath = ModelStorage;
130 ResultPath.push_back(0);
131 ResultPath.pop_back();
134 // Replace '%' with random chars.
135 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
136 if (ModelStorage[i] == '%')
137 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
140 // Try to open + create the file.
143 int RandomFD = ::open(ResultPath.begin(), O_RDWR | O_CREAT | O_EXCL, Mode);
144 if (RandomFD == -1) {
145 int SavedErrno = errno;
146 // If the file existed, try again, otherwise, error.
147 if (SavedErrno == errc::file_exists)
148 goto retry_random_path;
149 return error_code(SavedErrno, system_category());
153 return error_code::success();
158 error_code EC = sys::fs::exists(ResultPath.begin(), Exists);
162 goto retry_random_path;
163 return error_code::success();
167 if (error_code EC = sys::fs::create_directory(ResultPath.begin(), false)) {
168 if (EC == errc::file_exists)
169 goto retry_random_path;
172 return error_code::success();
175 llvm_unreachable("Invalid Type");
181 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
182 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
183 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
185 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
188 char fullpath[PATH_MAX];
190 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
191 if (realpath(fullpath, ret) == NULL)
193 if (stat(fullpath, &sb) != 0)
200 getprogpath(char ret[PATH_MAX], const char *bin)
204 /* First approach: absolute path. */
206 if (test_dir(ret, "/", bin) == 0)
211 /* Second approach: relative path. */
212 if (strchr(bin, '/') != NULL) {
214 if (getcwd(cwd, PATH_MAX) == NULL)
216 if (test_dir(ret, cwd, bin) == 0)
221 /* Third approach: $PATH */
222 if ((pv = getenv("PATH")) == NULL)
227 while ((t = strsep(&s, ":")) != NULL) {
228 if (test_dir(ret, t, bin) == 0) {
236 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
238 /// GetMainExecutable - Return the path to the main executable, given the
239 /// value of argv[0] from program startup.
240 std::string getMainExecutable(const char *argv0, void *MainAddr) {
241 #if defined(__APPLE__)
242 // On OS X the executable path is saved to the stack by dyld. Reading it
243 // from there is much faster than calling dladdr, especially for large
244 // binaries with symbols.
245 char exe_path[MAXPATHLEN];
246 uint32_t size = sizeof(exe_path);
247 if (_NSGetExecutablePath(exe_path, &size) == 0) {
248 char link_path[MAXPATHLEN];
249 if (realpath(exe_path, link_path))
252 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
253 defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
254 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 UniqueID file_status::getUniqueID() const {
297 return UniqueID(fs_st_dev, fs_st_ino);
300 error_code current_path(SmallVectorImpl<char> &result) {
303 const char *pwd = ::getenv("PWD");
304 llvm::sys::fs::file_status PWDStatus, DotStatus;
305 if (pwd && llvm::sys::path::is_absolute(pwd) &&
306 !llvm::sys::fs::status(pwd, PWDStatus) &&
307 !llvm::sys::fs::status(".", DotStatus) &&
308 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
309 result.append(pwd, pwd + strlen(pwd));
310 return error_code::success();
314 result.reserve(MAXPATHLEN);
317 result.reserve(1024);
321 if (::getcwd(result.data(), result.capacity()) == 0) {
322 // See if there was a real error.
323 if (errno != errc::not_enough_memory)
324 return error_code(errno, system_category());
325 // Otherwise there just wasn't enough space.
326 result.reserve(result.capacity() * 2);
331 result.set_size(strlen(result.data()));
332 return error_code::success();
335 error_code create_directory(const Twine &path, bool IgnoreExisting) {
336 SmallString<128> path_storage;
337 StringRef p = path.toNullTerminatedStringRef(path_storage);
339 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
340 if (errno != errc::file_exists || !IgnoreExisting)
341 return error_code(errno, system_category());
344 return error_code::success();
347 error_code create_hard_link(const Twine &to, const Twine &from) {
349 SmallString<128> from_storage;
350 SmallString<128> to_storage;
351 StringRef f = from.toNullTerminatedStringRef(from_storage);
352 StringRef t = to.toNullTerminatedStringRef(to_storage);
354 if (::link(t.begin(), f.begin()) == -1)
355 return error_code(errno, system_category());
357 return error_code::success();
360 error_code remove(const Twine &path, bool IgnoreNonExisting) {
361 SmallString<128> path_storage;
362 StringRef p = path.toNullTerminatedStringRef(path_storage);
365 if (stat(p.begin(), &buf) != 0) {
366 if (errno != errc::no_such_file_or_directory || !IgnoreNonExisting)
367 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 || !IgnoreNonExisting)
381 return error_code(errno, system_category());
384 return error_code::success();
387 error_code rename(const Twine &from, const Twine &to) {
389 SmallString<128> from_storage;
390 SmallString<128> to_storage;
391 StringRef f = from.toNullTerminatedStringRef(from_storage);
392 StringRef t = to.toNullTerminatedStringRef(to_storage);
394 if (::rename(f.begin(), t.begin()) == -1)
395 return error_code(errno, system_category());
397 return error_code::success();
400 error_code resize_file(const Twine &path, uint64_t size) {
401 SmallString<128> path_storage;
402 StringRef p = path.toNullTerminatedStringRef(path_storage);
404 if (::truncate(p.begin(), size) == -1)
405 return error_code(errno, system_category());
407 return error_code::success();
410 error_code exists(const Twine &path, bool &result) {
411 SmallString<128> path_storage;
412 StringRef p = path.toNullTerminatedStringRef(path_storage);
414 if (::access(p.begin(), F_OK) == -1) {
415 if (errno != errc::no_such_file_or_directory)
416 return error_code(errno, system_category());
421 return error_code::success();
424 bool can_write(const Twine &Path) {
425 SmallString<128> PathStorage;
426 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
427 return 0 == access(P.begin(), W_OK);
430 bool can_execute(const Twine &Path) {
431 SmallString<128> PathStorage;
432 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
434 if (0 != access(P.begin(), R_OK | X_OK))
437 if (0 != stat(P.begin(), &buf))
439 if (!S_ISREG(buf.st_mode))
444 bool equivalent(file_status A, file_status B) {
445 assert(status_known(A) && status_known(B));
446 return A.fs_st_dev == B.fs_st_dev &&
447 A.fs_st_ino == B.fs_st_ino;
450 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
451 file_status fsA, fsB;
452 if (error_code ec = status(A, fsA)) return ec;
453 if (error_code ec = status(B, fsB)) return ec;
454 result = equivalent(fsA, fsB);
455 return error_code::success();
458 static error_code fillStatus(int StatRet, const struct stat &Status,
459 file_status &Result) {
461 error_code ec(errno, system_category());
462 if (ec == errc::no_such_file_or_directory)
463 Result = file_status(file_type::file_not_found);
465 Result = file_status(file_type::status_error);
469 file_type Type = file_type::type_unknown;
471 if (S_ISDIR(Status.st_mode))
472 Type = file_type::directory_file;
473 else if (S_ISREG(Status.st_mode))
474 Type = file_type::regular_file;
475 else if (S_ISBLK(Status.st_mode))
476 Type = file_type::block_file;
477 else if (S_ISCHR(Status.st_mode))
478 Type = file_type::character_file;
479 else if (S_ISFIFO(Status.st_mode))
480 Type = file_type::fifo_file;
481 else if (S_ISSOCK(Status.st_mode))
482 Type = file_type::socket_file;
484 perms Perms = static_cast<perms>(Status.st_mode);
486 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
487 Status.st_uid, Status.st_gid, Status.st_size);
489 return error_code::success();
492 error_code status(const Twine &Path, file_status &Result) {
493 SmallString<128> PathStorage;
494 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
497 int StatRet = ::stat(P.begin(), &Status);
498 return fillStatus(StatRet, Status, Result);
501 error_code status(int FD, file_status &Result) {
503 int StatRet = ::fstat(FD, &Status);
504 return fillStatus(StatRet, Status, Result);
507 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
508 #if defined(HAVE_FUTIMENS)
510 Times[0].tv_sec = Time.toEpochTime();
511 Times[0].tv_nsec = 0;
513 if (::futimens(FD, Times))
514 return error_code(errno, system_category());
515 return error_code::success();
516 #elif defined(HAVE_FUTIMES)
518 Times[0].tv_sec = Time.toEpochTime();
519 Times[0].tv_usec = 0;
521 if (::futimes(FD, Times))
522 return error_code(errno, system_category());
523 return error_code::success();
525 #warning Missing futimes() and futimens()
526 return make_error_code(errc::not_supported);
530 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
535 // Figure out how large the file is.
536 struct stat FileInfo;
537 if (fstat(FD, &FileInfo) == -1)
538 return error_code(errno, system_category());
539 uint64_t FileSize = FileInfo.st_size;
543 else if (FileSize < Size) {
544 // We need to grow the file.
545 if (ftruncate(FD, Size) == -1)
546 return error_code(errno, system_category());
549 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
550 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
554 Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
555 if (Mapping == MAP_FAILED)
556 return error_code(errno, system_category());
557 return error_code::success();
560 mapped_file_region::mapped_file_region(const Twine &path,
568 // Make sure that the requested size fits within SIZE_T.
569 if (length > std::numeric_limits<size_t>::max()) {
570 ec = make_error_code(errc::invalid_argument);
574 SmallString<128> path_storage;
575 StringRef name = path.toNullTerminatedStringRef(path_storage);
576 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
577 int ofd = ::open(name.begin(), oflags);
579 ec = error_code(errno, system_category());
583 ec = init(ofd, true, offset);
588 mapped_file_region::mapped_file_region(int fd,
597 // Make sure that the requested size fits within SIZE_T.
598 if (length > std::numeric_limits<size_t>::max()) {
599 ec = make_error_code(errc::invalid_argument);
603 ec = init(fd, closefd, offset);
608 mapped_file_region::~mapped_file_region() {
610 ::munmap(Mapping, Size);
613 #if LLVM_HAS_RVALUE_REFERENCES
614 mapped_file_region::mapped_file_region(mapped_file_region &&other)
615 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
620 mapped_file_region::mapmode mapped_file_region::flags() const {
621 assert(Mapping && "Mapping failed but used anyway!");
625 uint64_t mapped_file_region::size() const {
626 assert(Mapping && "Mapping failed but used anyway!");
630 char *mapped_file_region::data() const {
631 assert(Mapping && "Mapping failed but used anyway!");
632 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
633 return reinterpret_cast<char*>(Mapping);
636 const char *mapped_file_region::const_data() const {
637 assert(Mapping && "Mapping failed but used anyway!");
638 return reinterpret_cast<const char*>(Mapping);
641 int mapped_file_region::alignment() {
642 return process::get_self()->page_size();
645 error_code detail::directory_iterator_construct(detail::DirIterState &it,
647 SmallString<128> path_null(path);
648 DIR *directory = ::opendir(path_null.c_str());
650 return error_code(errno, system_category());
652 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
653 // Add something for replace_filename to replace.
654 path::append(path_null, ".");
655 it.CurrentEntry = directory_entry(path_null.str());
656 return directory_iterator_increment(it);
659 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
660 if (it.IterationHandle)
661 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
662 it.IterationHandle = 0;
663 it.CurrentEntry = directory_entry();
664 return error_code::success();
667 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
669 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
670 if (cur_dir == 0 && errno != 0) {
671 return error_code(errno, system_category());
672 } else if (cur_dir != 0) {
673 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
674 if ((name.size() == 1 && name[0] == '.') ||
675 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
676 return directory_iterator_increment(it);
677 it.CurrentEntry.replace_filename(name);
679 return directory_iterator_destruct(it);
681 return error_code::success();
684 error_code get_magic(const Twine &path, uint32_t len,
685 SmallVectorImpl<char> &result) {
686 SmallString<128> PathStorage;
687 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
691 std::FILE *file = std::fopen(Path.data(), "rb");
693 return error_code(errno, system_category());
699 size_t size = std::fread(result.data(), 1, len, file);
700 if (std::ferror(file) != 0) {
702 return error_code(errno, system_category());
703 } else if (size != len) {
704 if (std::feof(file) != 0) {
706 result.set_size(size);
707 return make_error_code(errc::value_too_large);
711 result.set_size(size);
712 return error_code::success();
715 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
716 bool map_writable, void *&result) {
717 SmallString<128> path_storage;
718 StringRef name = path.toNullTerminatedStringRef(path_storage);
719 int oflags = map_writable ? O_RDWR : O_RDONLY;
720 int ofd = ::open(name.begin(), oflags);
722 return error_code(errno, system_category());
724 int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
725 int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
729 result = ::mmap(0, size, prot, flags, fd, file_offset);
730 if (result == MAP_FAILED) {
731 return error_code(errno, system_category());
734 return error_code::success();
737 error_code unmap_file_pages(void *base, size_t size) {
738 if ( ::munmap(base, size) == -1 )
739 return error_code(errno, system_category());
741 return error_code::success();
744 error_code openFileForRead(const Twine &Name, int &ResultFD) {
745 SmallString<128> Storage;
746 StringRef P = Name.toNullTerminatedStringRef(Storage);
747 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
749 return error_code(errno, system_category());
751 return error_code::success();
754 error_code openFileForWrite(const Twine &Name, int &ResultFD,
755 sys::fs::OpenFlags Flags, unsigned Mode) {
756 // Verify that we don't have both "append" and "excl".
757 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
758 "Cannot specify both 'excl' and 'append' file creation flags!");
760 int OpenFlags = O_WRONLY | O_CREAT;
762 if (Flags & F_Append)
763 OpenFlags |= O_APPEND;
765 OpenFlags |= O_TRUNC;
770 SmallString<128> Storage;
771 StringRef P = Name.toNullTerminatedStringRef(Storage);
772 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
774 return error_code(errno, system_category());
776 return error_code::success();
779 } // end namespace fs
783 bool home_directory(SmallVectorImpl<char> &result) {
784 if (char *RequestedDir = getenv("HOME")) {
786 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
793 } // end namespace path
795 } // end namespace sys
796 } // end namespace llvm