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();
109 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
110 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
111 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
113 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
116 char fullpath[PATH_MAX];
118 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
119 if (realpath(fullpath, ret) == NULL)
121 if (stat(fullpath, &sb) != 0)
128 getprogpath(char ret[PATH_MAX], const char *bin)
132 /* First approach: absolute path. */
134 if (test_dir(ret, "/", bin) == 0)
139 /* Second approach: relative path. */
140 if (strchr(bin, '/') != NULL) {
142 if (getcwd(cwd, PATH_MAX) == NULL)
144 if (test_dir(ret, cwd, bin) == 0)
149 /* Third approach: $PATH */
150 if ((pv = getenv("PATH")) == NULL)
155 while ((t = strsep(&s, ":")) != NULL) {
156 if (test_dir(ret, t, bin) == 0) {
164 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
166 /// GetMainExecutable - Return the path to the main executable, given the
167 /// value of argv[0] from program startup.
168 std::string getMainExecutable(const char *argv0, void *MainAddr) {
169 #if defined(__APPLE__)
170 // On OS X the executable path is saved to the stack by dyld. Reading it
171 // from there is much faster than calling dladdr, especially for large
172 // binaries with symbols.
173 char exe_path[MAXPATHLEN];
174 uint32_t size = sizeof(exe_path);
175 if (_NSGetExecutablePath(exe_path, &size) == 0) {
176 char link_path[MAXPATHLEN];
177 if (realpath(exe_path, link_path))
180 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
181 defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
182 defined(__FreeBSD_kernel__)
183 char exe_path[PATH_MAX];
185 if (getprogpath(exe_path, argv0) != NULL)
187 #elif defined(__linux__) || defined(__CYGWIN__)
188 char exe_path[MAXPATHLEN];
189 StringRef aPath("/proc/self/exe");
190 if (sys::fs::exists(aPath)) {
191 // /proc is not always mounted under Linux (chroot for example).
192 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
194 return StringRef(exe_path, len);
196 // Fall back to the classical detection.
197 if (getprogpath(exe_path, argv0) != NULL)
200 #elif defined(HAVE_DLFCN_H)
201 // Use dladdr to get executable path if available.
203 int err = dladdr(MainAddr, &DLInfo);
207 // If the filename is a symlink, we need to resolve and return the location of
208 // the actual executable.
209 char link_path[MAXPATHLEN];
210 if (realpath(DLInfo.dli_fname, link_path))
213 #error GetMainExecutable is not implemented on this host yet.
218 TimeValue file_status::getLastModificationTime() const {
220 Ret.fromEpochTime(fs_st_mtime);
224 UniqueID file_status::getUniqueID() const {
225 return UniqueID(fs_st_dev, fs_st_ino);
228 error_code current_path(SmallVectorImpl<char> &result) {
231 const char *pwd = ::getenv("PWD");
232 llvm::sys::fs::file_status PWDStatus, DotStatus;
233 if (pwd && llvm::sys::path::is_absolute(pwd) &&
234 !llvm::sys::fs::status(pwd, PWDStatus) &&
235 !llvm::sys::fs::status(".", DotStatus) &&
236 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
237 result.append(pwd, pwd + strlen(pwd));
238 return error_code::success();
242 result.reserve(MAXPATHLEN);
245 result.reserve(1024);
249 if (::getcwd(result.data(), result.capacity()) == 0) {
250 // See if there was a real error.
251 if (errno != errc::not_enough_memory)
252 return error_code(errno, system_category());
253 // Otherwise there just wasn't enough space.
254 result.reserve(result.capacity() * 2);
259 result.set_size(strlen(result.data()));
260 return error_code::success();
263 error_code create_directory(const Twine &path, bool IgnoreExisting) {
264 SmallString<128> path_storage;
265 StringRef p = path.toNullTerminatedStringRef(path_storage);
267 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
268 if (errno != errc::file_exists || !IgnoreExisting)
269 return error_code(errno, system_category());
272 return error_code::success();
275 error_code create_hard_link(const Twine &to, const Twine &from) {
277 SmallString<128> from_storage;
278 SmallString<128> to_storage;
279 StringRef f = from.toNullTerminatedStringRef(from_storage);
280 StringRef t = to.toNullTerminatedStringRef(to_storage);
282 if (::link(t.begin(), f.begin()) == -1)
283 return error_code(errno, system_category());
285 return error_code::success();
288 error_code create_symbolic_link(const Twine &to, const Twine &from) {
290 SmallString<128> from_storage;
291 SmallString<128> to_storage;
292 StringRef f = from.toNullTerminatedStringRef(from_storage);
293 StringRef t = to.toNullTerminatedStringRef(to_storage);
295 if (::symlink(t.begin(), f.begin()) == -1)
296 return error_code(errno, system_category());
298 return error_code::success();
301 error_code remove(const Twine &path, bool IgnoreNonExisting) {
302 SmallString<128> path_storage;
303 StringRef p = path.toNullTerminatedStringRef(path_storage);
306 if (stat(p.begin(), &buf) != 0) {
307 if (errno != errc::no_such_file_or_directory || !IgnoreNonExisting)
308 return error_code(errno, system_category());
309 return error_code::success();
312 // Note: this check catches strange situations. In all cases, LLVM should
313 // only be involved in the creation and deletion of regular files. This
314 // check ensures that what we're trying to erase is a regular file. It
315 // effectively prevents LLVM from erasing things like /dev/null, any block
316 // special file, or other things that aren't "regular" files.
317 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
318 return make_error_code(errc::operation_not_permitted);
320 if (::remove(p.begin()) == -1) {
321 if (errno != errc::no_such_file_or_directory || !IgnoreNonExisting)
322 return error_code(errno, system_category());
325 return error_code::success();
328 error_code rename(const Twine &from, const Twine &to) {
330 SmallString<128> from_storage;
331 SmallString<128> to_storage;
332 StringRef f = from.toNullTerminatedStringRef(from_storage);
333 StringRef t = to.toNullTerminatedStringRef(to_storage);
335 if (::rename(f.begin(), t.begin()) == -1)
336 return error_code(errno, system_category());
338 return error_code::success();
341 error_code resize_file(const Twine &path, uint64_t size) {
342 SmallString<128> path_storage;
343 StringRef p = path.toNullTerminatedStringRef(path_storage);
345 if (::truncate(p.begin(), size) == -1)
346 return error_code(errno, system_category());
348 return error_code::success();
351 error_code exists(const Twine &path, bool &result) {
352 SmallString<128> path_storage;
353 StringRef p = path.toNullTerminatedStringRef(path_storage);
355 if (::access(p.begin(), F_OK) == -1) {
356 if (errno != errc::no_such_file_or_directory)
357 return error_code(errno, system_category());
362 return error_code::success();
365 bool can_write(const Twine &Path) {
366 SmallString<128> PathStorage;
367 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
368 return 0 == access(P.begin(), W_OK);
371 bool can_execute(const Twine &Path) {
372 SmallString<128> PathStorage;
373 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
375 if (0 != access(P.begin(), R_OK | X_OK))
378 if (0 != stat(P.begin(), &buf))
380 if (!S_ISREG(buf.st_mode))
385 bool equivalent(file_status A, file_status B) {
386 assert(status_known(A) && status_known(B));
387 return A.fs_st_dev == B.fs_st_dev &&
388 A.fs_st_ino == B.fs_st_ino;
391 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
392 file_status fsA, fsB;
393 if (error_code ec = status(A, fsA)) return ec;
394 if (error_code ec = status(B, fsB)) return ec;
395 result = equivalent(fsA, fsB);
396 return error_code::success();
399 static error_code fillStatus(int StatRet, const struct stat &Status,
400 file_status &Result) {
402 error_code ec(errno, system_category());
403 if (ec == errc::no_such_file_or_directory)
404 Result = file_status(file_type::file_not_found);
406 Result = file_status(file_type::status_error);
410 file_type Type = file_type::type_unknown;
412 if (S_ISDIR(Status.st_mode))
413 Type = file_type::directory_file;
414 else if (S_ISREG(Status.st_mode))
415 Type = file_type::regular_file;
416 else if (S_ISBLK(Status.st_mode))
417 Type = file_type::block_file;
418 else if (S_ISCHR(Status.st_mode))
419 Type = file_type::character_file;
420 else if (S_ISFIFO(Status.st_mode))
421 Type = file_type::fifo_file;
422 else if (S_ISSOCK(Status.st_mode))
423 Type = file_type::socket_file;
425 perms Perms = static_cast<perms>(Status.st_mode);
427 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
428 Status.st_uid, Status.st_gid, Status.st_size);
430 return error_code::success();
433 error_code status(const Twine &Path, file_status &Result) {
434 SmallString<128> PathStorage;
435 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
438 int StatRet = ::stat(P.begin(), &Status);
439 return fillStatus(StatRet, Status, Result);
442 error_code status(int FD, file_status &Result) {
444 int StatRet = ::fstat(FD, &Status);
445 return fillStatus(StatRet, Status, Result);
448 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
449 #if defined(HAVE_FUTIMENS)
451 Times[0].tv_sec = Time.toEpochTime();
452 Times[0].tv_nsec = 0;
454 if (::futimens(FD, Times))
455 return error_code(errno, system_category());
456 return error_code::success();
457 #elif defined(HAVE_FUTIMES)
459 Times[0].tv_sec = Time.toEpochTime();
460 Times[0].tv_usec = 0;
462 if (::futimes(FD, Times))
463 return error_code(errno, system_category());
464 return error_code::success();
466 #warning Missing futimes() and futimens()
467 return make_error_code(errc::not_supported);
471 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
476 // Figure out how large the file is.
477 struct stat FileInfo;
478 if (fstat(FD, &FileInfo) == -1)
479 return error_code(errno, system_category());
480 uint64_t FileSize = FileInfo.st_size;
484 else if (FileSize < Size) {
485 // We need to grow the file.
486 if (ftruncate(FD, Size) == -1)
487 return error_code(errno, system_category());
490 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
491 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
495 Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
496 if (Mapping == MAP_FAILED)
497 return error_code(errno, system_category());
498 return error_code::success();
501 mapped_file_region::mapped_file_region(const Twine &path,
509 // Make sure that the requested size fits within SIZE_T.
510 if (length > std::numeric_limits<size_t>::max()) {
511 ec = make_error_code(errc::invalid_argument);
515 SmallString<128> path_storage;
516 StringRef name = path.toNullTerminatedStringRef(path_storage);
517 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
518 int ofd = ::open(name.begin(), oflags);
520 ec = error_code(errno, system_category());
524 ec = init(ofd, true, offset);
529 mapped_file_region::mapped_file_region(int fd,
538 // Make sure that the requested size fits within SIZE_T.
539 if (length > std::numeric_limits<size_t>::max()) {
540 ec = make_error_code(errc::invalid_argument);
544 ec = init(fd, closefd, offset);
549 mapped_file_region::~mapped_file_region() {
551 ::munmap(Mapping, Size);
554 mapped_file_region::mapped_file_region(mapped_file_region &&other)
555 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
559 mapped_file_region::mapmode mapped_file_region::flags() const {
560 assert(Mapping && "Mapping failed but used anyway!");
564 uint64_t mapped_file_region::size() const {
565 assert(Mapping && "Mapping failed but used anyway!");
569 char *mapped_file_region::data() const {
570 assert(Mapping && "Mapping failed but used anyway!");
571 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
572 return reinterpret_cast<char*>(Mapping);
575 const char *mapped_file_region::const_data() const {
576 assert(Mapping && "Mapping failed but used anyway!");
577 return reinterpret_cast<const char*>(Mapping);
580 int mapped_file_region::alignment() {
581 return process::get_self()->page_size();
584 error_code detail::directory_iterator_construct(detail::DirIterState &it,
586 SmallString<128> path_null(path);
587 DIR *directory = ::opendir(path_null.c_str());
589 return error_code(errno, system_category());
591 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
592 // Add something for replace_filename to replace.
593 path::append(path_null, ".");
594 it.CurrentEntry = directory_entry(path_null.str());
595 return directory_iterator_increment(it);
598 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
599 if (it.IterationHandle)
600 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
601 it.IterationHandle = 0;
602 it.CurrentEntry = directory_entry();
603 return error_code::success();
606 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
608 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
609 if (cur_dir == 0 && errno != 0) {
610 return error_code(errno, system_category());
611 } else if (cur_dir != 0) {
612 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
613 if ((name.size() == 1 && name[0] == '.') ||
614 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
615 return directory_iterator_increment(it);
616 it.CurrentEntry.replace_filename(name);
618 return directory_iterator_destruct(it);
620 return error_code::success();
623 error_code get_magic(const Twine &path, uint32_t len,
624 SmallVectorImpl<char> &result) {
625 SmallString<128> PathStorage;
626 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
630 std::FILE *file = std::fopen(Path.data(), "rb");
632 return error_code(errno, system_category());
638 size_t size = std::fread(result.data(), 1, len, file);
639 if (std::ferror(file) != 0) {
641 return error_code(errno, system_category());
642 } else if (size != len) {
643 if (std::feof(file) != 0) {
645 result.set_size(size);
646 return make_error_code(errc::value_too_large);
650 result.set_size(size);
651 return error_code::success();
654 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
655 bool map_writable, void *&result) {
656 SmallString<128> path_storage;
657 StringRef name = path.toNullTerminatedStringRef(path_storage);
658 int oflags = map_writable ? O_RDWR : O_RDONLY;
659 int ofd = ::open(name.begin(), oflags);
661 return error_code(errno, system_category());
663 int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
664 int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
668 result = ::mmap(0, size, prot, flags, fd, file_offset);
669 if (result == MAP_FAILED) {
670 return error_code(errno, system_category());
673 return error_code::success();
676 error_code unmap_file_pages(void *base, size_t size) {
677 if ( ::munmap(base, size) == -1 )
678 return error_code(errno, system_category());
680 return error_code::success();
683 error_code openFileForRead(const Twine &Name, int &ResultFD) {
684 SmallString<128> Storage;
685 StringRef P = Name.toNullTerminatedStringRef(Storage);
686 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
688 return error_code(errno, system_category());
690 return error_code::success();
693 error_code openFileForWrite(const Twine &Name, int &ResultFD,
694 sys::fs::OpenFlags Flags, unsigned Mode) {
695 // Verify that we don't have both "append" and "excl".
696 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
697 "Cannot specify both 'excl' and 'append' file creation flags!");
699 int OpenFlags = O_CREAT;
704 OpenFlags |= O_WRONLY;
706 if (Flags & F_Append)
707 OpenFlags |= O_APPEND;
709 OpenFlags |= O_TRUNC;
714 SmallString<128> Storage;
715 StringRef P = Name.toNullTerminatedStringRef(Storage);
716 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
718 return error_code(errno, system_category());
720 return error_code::success();
723 } // end namespace fs
727 bool home_directory(SmallVectorImpl<char> &result) {
728 if (char *RequestedDir = getenv("HOME")) {
730 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
737 } // end namespace path
739 } // end namespace sys
740 } // end namespace llvm