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
63 #include <sys/types.h>
64 #if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__ANDROID__)
65 #include <sys/statvfs.h>
66 #define STATVFS statvfs
67 #define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
70 #include <sys/param.h>
71 #elif defined(__ANDROID__)
74 #include <sys/mount.h>
76 #define STATVFS statfs
77 #define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
86 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
87 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
88 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
90 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
93 char fullpath[PATH_MAX];
95 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
96 if (!realpath(fullpath, ret))
98 if (stat(fullpath, &sb) != 0)
105 getprogpath(char ret[PATH_MAX], const char *bin)
109 /* First approach: absolute path. */
111 if (test_dir(ret, "/", bin) == 0)
116 /* Second approach: relative path. */
117 if (strchr(bin, '/')) {
119 if (!getcwd(cwd, PATH_MAX))
121 if (test_dir(ret, cwd, bin) == 0)
126 /* Third approach: $PATH */
127 if ((pv = getenv("PATH")) == nullptr)
132 while ((t = strsep(&s, ":")) != nullptr) {
133 if (test_dir(ret, t, bin) == 0) {
141 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
143 /// GetMainExecutable - Return the path to the main executable, given the
144 /// value of argv[0] from program startup.
145 std::string getMainExecutable(const char *argv0, void *MainAddr) {
146 #if defined(__APPLE__)
147 // On OS X the executable path is saved to the stack by dyld. Reading it
148 // from there is much faster than calling dladdr, especially for large
149 // binaries with symbols.
150 char exe_path[MAXPATHLEN];
151 uint32_t size = sizeof(exe_path);
152 if (_NSGetExecutablePath(exe_path, &size) == 0) {
153 char link_path[MAXPATHLEN];
154 if (realpath(exe_path, link_path))
157 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
158 defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
159 defined(__FreeBSD_kernel__)
160 char exe_path[PATH_MAX];
162 if (getprogpath(exe_path, argv0) != NULL)
164 #elif defined(__linux__) || defined(__CYGWIN__)
165 char exe_path[MAXPATHLEN];
166 StringRef aPath("/proc/self/exe");
167 if (sys::fs::exists(aPath)) {
168 // /proc is not always mounted under Linux (chroot for example).
169 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
171 return std::string(exe_path, len);
173 // Fall back to the classical detection.
174 if (getprogpath(exe_path, argv0))
177 #elif defined(HAVE_DLFCN_H)
178 // Use dladdr to get executable path if available.
180 int err = dladdr(MainAddr, &DLInfo);
184 // If the filename is a symlink, we need to resolve and return the location of
185 // the actual executable.
186 char link_path[MAXPATHLEN];
187 if (realpath(DLInfo.dli_fname, link_path))
190 #error GetMainExecutable is not implemented on this host yet.
195 TimeValue file_status::getLastAccessedTime() const {
197 Ret.fromEpochTime(fs_st_atime);
201 TimeValue file_status::getLastModificationTime() const {
203 Ret.fromEpochTime(fs_st_mtime);
207 UniqueID file_status::getUniqueID() const {
208 return UniqueID(fs_st_dev, fs_st_ino);
211 ErrorOr<space_info> disk_space(const Twine &Path) {
213 if (::STATVFS(Path.str().c_str(), &Vfs))
214 return std::error_code(errno, std::generic_category());
215 auto FrSize = STATVFS_F_FRSIZE(Vfs);
216 space_info SpaceInfo;
217 SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
218 SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
219 SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
223 std::error_code current_path(SmallVectorImpl<char> &result) {
226 const char *pwd = ::getenv("PWD");
227 llvm::sys::fs::file_status PWDStatus, DotStatus;
228 if (pwd && llvm::sys::path::is_absolute(pwd) &&
229 !llvm::sys::fs::status(pwd, PWDStatus) &&
230 !llvm::sys::fs::status(".", DotStatus) &&
231 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
232 result.append(pwd, pwd + strlen(pwd));
233 return std::error_code();
237 result.reserve(MAXPATHLEN);
240 result.reserve(1024);
244 if (::getcwd(result.data(), result.capacity()) == nullptr) {
245 // See if there was a real error.
247 return std::error_code(errno, std::generic_category());
248 // Otherwise there just wasn't enough space.
249 result.reserve(result.capacity() * 2);
254 result.set_size(strlen(result.data()));
255 return std::error_code();
258 std::error_code create_directory(const Twine &path, bool IgnoreExisting,
260 SmallString<128> path_storage;
261 StringRef p = path.toNullTerminatedStringRef(path_storage);
263 if (::mkdir(p.begin(), Perms) == -1) {
264 if (errno != EEXIST || !IgnoreExisting)
265 return std::error_code(errno, std::generic_category());
268 return std::error_code();
271 // Note that we are using symbolic link because hard links are not supported by
272 // all filesystems (SMB doesn't).
273 std::error_code create_link(const Twine &to, const Twine &from) {
275 SmallString<128> from_storage;
276 SmallString<128> to_storage;
277 StringRef f = from.toNullTerminatedStringRef(from_storage);
278 StringRef t = to.toNullTerminatedStringRef(to_storage);
280 if (::symlink(t.begin(), f.begin()) == -1)
281 return std::error_code(errno, std::generic_category());
283 return std::error_code();
286 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
287 SmallString<128> path_storage;
288 StringRef p = path.toNullTerminatedStringRef(path_storage);
291 if (lstat(p.begin(), &buf) != 0) {
292 if (errno != ENOENT || !IgnoreNonExisting)
293 return std::error_code(errno, std::generic_category());
294 return std::error_code();
297 // Note: this check catches strange situations. In all cases, LLVM should
298 // only be involved in the creation and deletion of regular files. This
299 // check ensures that what we're trying to erase is a regular file. It
300 // effectively prevents LLVM from erasing things like /dev/null, any block
301 // special file, or other things that aren't "regular" files.
302 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
303 return make_error_code(errc::operation_not_permitted);
305 if (::remove(p.begin()) == -1) {
306 if (errno != ENOENT || !IgnoreNonExisting)
307 return std::error_code(errno, std::generic_category());
310 return std::error_code();
313 std::error_code rename(const Twine &from, const Twine &to) {
315 SmallString<128> from_storage;
316 SmallString<128> to_storage;
317 StringRef f = from.toNullTerminatedStringRef(from_storage);
318 StringRef t = to.toNullTerminatedStringRef(to_storage);
320 if (::rename(f.begin(), t.begin()) == -1)
321 return std::error_code(errno, std::generic_category());
323 return std::error_code();
326 std::error_code resize_file(int FD, uint64_t Size) {
327 if (::ftruncate(FD, Size) == -1)
328 return std::error_code(errno, std::generic_category());
330 return std::error_code();
333 static int convertAccessMode(AccessMode Mode) {
335 case AccessMode::Exist:
337 case AccessMode::Write:
339 case AccessMode::Execute:
340 return R_OK | X_OK; // scripts also need R_OK.
342 llvm_unreachable("invalid enum");
345 std::error_code access(const Twine &Path, AccessMode Mode) {
346 SmallString<128> PathStorage;
347 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
349 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
350 return std::error_code(errno, std::generic_category());
352 if (Mode == AccessMode::Execute) {
353 // Don't say that directories are executable.
355 if (0 != stat(P.begin(), &buf))
356 return errc::permission_denied;
357 if (!S_ISREG(buf.st_mode))
358 return errc::permission_denied;
361 return std::error_code();
364 bool can_execute(const Twine &Path) {
365 return !access(Path, AccessMode::Execute);
368 bool equivalent(file_status A, file_status B) {
369 assert(status_known(A) && status_known(B));
370 return A.fs_st_dev == B.fs_st_dev &&
371 A.fs_st_ino == B.fs_st_ino;
374 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
375 file_status fsA, fsB;
376 if (std::error_code ec = status(A, fsA))
378 if (std::error_code ec = status(B, fsB))
380 result = equivalent(fsA, fsB);
381 return std::error_code();
384 static std::error_code fillStatus(int StatRet, const struct stat &Status,
385 file_status &Result) {
387 std::error_code ec(errno, std::generic_category());
388 if (ec == errc::no_such_file_or_directory)
389 Result = file_status(file_type::file_not_found);
391 Result = file_status(file_type::status_error);
395 file_type Type = file_type::type_unknown;
397 if (S_ISDIR(Status.st_mode))
398 Type = file_type::directory_file;
399 else if (S_ISREG(Status.st_mode))
400 Type = file_type::regular_file;
401 else if (S_ISBLK(Status.st_mode))
402 Type = file_type::block_file;
403 else if (S_ISCHR(Status.st_mode))
404 Type = file_type::character_file;
405 else if (S_ISFIFO(Status.st_mode))
406 Type = file_type::fifo_file;
407 else if (S_ISSOCK(Status.st_mode))
408 Type = file_type::socket_file;
410 perms Perms = static_cast<perms>(Status.st_mode);
412 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_atime,
413 Status.st_mtime, Status.st_uid, Status.st_gid,
416 return std::error_code();
419 std::error_code status(const Twine &Path, file_status &Result) {
420 SmallString<128> PathStorage;
421 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
424 int StatRet = ::stat(P.begin(), &Status);
425 return fillStatus(StatRet, Status, Result);
428 std::error_code status(int FD, file_status &Result) {
430 int StatRet = ::fstat(FD, &Status);
431 return fillStatus(StatRet, Status, Result);
434 std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
435 #if defined(HAVE_FUTIMENS)
437 Times[0].tv_sec = Time.toEpochTime();
438 Times[0].tv_nsec = 0;
440 if (::futimens(FD, Times))
441 return std::error_code(errno, std::generic_category());
442 return std::error_code();
443 #elif defined(HAVE_FUTIMES)
445 Times[0].tv_sec = Time.toEpochTime();
446 Times[0].tv_usec = 0;
448 if (::futimes(FD, Times))
449 return std::error_code(errno, std::generic_category());
450 return std::error_code();
452 #warning Missing futimes() and futimens()
453 return make_error_code(errc::function_not_supported);
457 std::error_code mapped_file_region::init(int FD, uint64_t Offset,
461 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
462 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
463 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
464 if (Mapping == MAP_FAILED)
465 return std::error_code(errno, std::generic_category());
466 return std::error_code();
469 mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
470 uint64_t offset, std::error_code &ec)
471 : Size(length), Mapping() {
472 // Make sure that the requested size fits within SIZE_T.
473 if (length > std::numeric_limits<size_t>::max()) {
474 ec = make_error_code(errc::invalid_argument);
478 ec = init(fd, offset, mode);
483 mapped_file_region::~mapped_file_region() {
485 ::munmap(Mapping, Size);
488 uint64_t mapped_file_region::size() const {
489 assert(Mapping && "Mapping failed but used anyway!");
493 char *mapped_file_region::data() const {
494 assert(Mapping && "Mapping failed but used anyway!");
495 return reinterpret_cast<char*>(Mapping);
498 const char *mapped_file_region::const_data() const {
499 assert(Mapping && "Mapping failed but used anyway!");
500 return reinterpret_cast<const char*>(Mapping);
503 int mapped_file_region::alignment() {
504 return Process::getPageSize();
507 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
509 SmallString<128> path_null(path);
510 DIR *directory = ::opendir(path_null.c_str());
512 return std::error_code(errno, std::generic_category());
514 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
515 // Add something for replace_filename to replace.
516 path::append(path_null, ".");
517 it.CurrentEntry = directory_entry(path_null.str());
518 return directory_iterator_increment(it);
521 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
522 if (it.IterationHandle)
523 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
524 it.IterationHandle = 0;
525 it.CurrentEntry = directory_entry();
526 return std::error_code();
529 std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
531 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
532 if (cur_dir == nullptr && errno != 0) {
533 return std::error_code(errno, std::generic_category());
534 } else if (cur_dir != nullptr) {
535 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
536 if ((name.size() == 1 && name[0] == '.') ||
537 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
538 return directory_iterator_increment(it);
539 it.CurrentEntry.replace_filename(name);
541 return directory_iterator_destruct(it);
543 return std::error_code();
546 std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
547 SmallString<128> Storage;
548 StringRef P = Name.toNullTerminatedStringRef(Storage);
549 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
551 return std::error_code(errno, std::generic_category());
553 return std::error_code();
556 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
557 sys::fs::OpenFlags Flags, unsigned Mode) {
558 // Verify that we don't have both "append" and "excl".
559 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
560 "Cannot specify both 'excl' and 'append' file creation flags!");
562 int OpenFlags = O_CREAT;
567 OpenFlags |= O_WRONLY;
569 if (Flags & F_Append)
570 OpenFlags |= O_APPEND;
572 OpenFlags |= O_TRUNC;
577 SmallString<128> Storage;
578 StringRef P = Name.toNullTerminatedStringRef(Storage);
579 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
581 return std::error_code(errno, std::generic_category());
583 return std::error_code();
586 } // end namespace fs
590 bool home_directory(SmallVectorImpl<char> &result) {
591 if (char *RequestedDir = getenv("HOME")) {
593 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
600 static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
601 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
602 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
603 // macros defined in <unistd.h> on darwin >= 9
604 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
605 : _CS_DARWIN_USER_CACHE_DIR;
606 size_t ConfLen = confstr(ConfName, nullptr, 0);
609 Result.resize(ConfLen);
610 ConfLen = confstr(ConfName, Result.data(), Result.size());
611 } while (ConfLen > 0 && ConfLen != Result.size());
614 assert(Result.back() == 0);
625 static bool getUserCacheDir(SmallVectorImpl<char> &Result) {
626 // First try using XDG_CACHE_HOME env variable,
627 // as specified in XDG Base Directory Specification at
628 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
629 if (const char *XdgCacheDir = std::getenv("XDG_CACHE_HOME")) {
631 Result.append(XdgCacheDir, XdgCacheDir + strlen(XdgCacheDir));
635 // Try Darwin configuration query
636 if (getDarwinConfDir(false, Result))
639 // Use "$HOME/.cache" if $HOME is available
640 if (home_directory(Result)) {
641 append(Result, ".cache");
648 static const char *getEnvTempDir() {
649 // Check whether the temporary directory is specified by an environment
651 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
652 for (const char *Env : EnvironmentVariables) {
653 if (const char *Dir = std::getenv(Env))
660 static const char *getDefaultTempDir(bool ErasedOnReboot) {
671 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
674 if (ErasedOnReboot) {
675 // There is no env variable for the cache directory.
676 if (const char *RequestedDir = getEnvTempDir()) {
677 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
682 if (getDarwinConfDir(ErasedOnReboot, Result))
685 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
686 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
689 } // end namespace path
691 } // end namespace sys
692 } // end namespace llvm