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 #include <sys/mount.h>
72 #elif defined(__ANDROID__)
75 #include <sys/mount.h>
77 #define STATVFS statfs
78 #define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
87 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
88 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
89 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
91 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
94 char fullpath[PATH_MAX];
96 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
97 if (!realpath(fullpath, ret))
99 if (stat(fullpath, &sb) != 0)
106 getprogpath(char ret[PATH_MAX], const char *bin)
110 /* First approach: absolute path. */
112 if (test_dir(ret, "/", bin) == 0)
117 /* Second approach: relative path. */
118 if (strchr(bin, '/')) {
120 if (!getcwd(cwd, PATH_MAX))
122 if (test_dir(ret, cwd, bin) == 0)
127 /* Third approach: $PATH */
128 if ((pv = getenv("PATH")) == nullptr)
133 while ((t = strsep(&s, ":")) != nullptr) {
134 if (test_dir(ret, t, bin) == 0) {
142 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
144 /// GetMainExecutable - Return the path to the main executable, given the
145 /// value of argv[0] from program startup.
146 std::string getMainExecutable(const char *argv0, void *MainAddr) {
147 #if defined(__APPLE__)
148 // On OS X the executable path is saved to the stack by dyld. Reading it
149 // from there is much faster than calling dladdr, especially for large
150 // binaries with symbols.
151 char exe_path[MAXPATHLEN];
152 uint32_t size = sizeof(exe_path);
153 if (_NSGetExecutablePath(exe_path, &size) == 0) {
154 char link_path[MAXPATHLEN];
155 if (realpath(exe_path, link_path))
158 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
159 defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
160 defined(__FreeBSD_kernel__)
161 char exe_path[PATH_MAX];
163 if (getprogpath(exe_path, argv0) != NULL)
165 #elif defined(__linux__) || defined(__CYGWIN__)
166 char exe_path[MAXPATHLEN];
167 StringRef aPath("/proc/self/exe");
168 if (sys::fs::exists(aPath)) {
169 // /proc is not always mounted under Linux (chroot for example).
170 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
172 return std::string(exe_path, len);
174 // Fall back to the classical detection.
175 if (getprogpath(exe_path, argv0))
178 #elif defined(HAVE_DLFCN_H)
179 // Use dladdr to get executable path if available.
181 int err = dladdr(MainAddr, &DLInfo);
185 // If the filename is a symlink, we need to resolve and return the location of
186 // the actual executable.
187 char link_path[MAXPATHLEN];
188 if (realpath(DLInfo.dli_fname, link_path))
191 #error GetMainExecutable is not implemented on this host yet.
196 TimeValue file_status::getLastAccessedTime() const {
198 Ret.fromEpochTime(fs_st_atime);
202 TimeValue file_status::getLastModificationTime() const {
204 Ret.fromEpochTime(fs_st_mtime);
208 UniqueID file_status::getUniqueID() const {
209 return UniqueID(fs_st_dev, fs_st_ino);
212 ErrorOr<space_info> disk_space(const Twine &Path) {
214 if (::STATVFS(Path.str().c_str(), &Vfs))
215 return std::error_code(errno, std::generic_category());
216 auto FrSize = STATVFS_F_FRSIZE(Vfs);
217 space_info SpaceInfo;
218 SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
219 SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
220 SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
224 std::error_code current_path(SmallVectorImpl<char> &result) {
227 const char *pwd = ::getenv("PWD");
228 llvm::sys::fs::file_status PWDStatus, DotStatus;
229 if (pwd && llvm::sys::path::is_absolute(pwd) &&
230 !llvm::sys::fs::status(pwd, PWDStatus) &&
231 !llvm::sys::fs::status(".", DotStatus) &&
232 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
233 result.append(pwd, pwd + strlen(pwd));
234 return std::error_code();
238 result.reserve(MAXPATHLEN);
241 result.reserve(1024);
245 if (::getcwd(result.data(), result.capacity()) == nullptr) {
246 // See if there was a real error.
248 return std::error_code(errno, std::generic_category());
249 // Otherwise there just wasn't enough space.
250 result.reserve(result.capacity() * 2);
255 result.set_size(strlen(result.data()));
256 return std::error_code();
259 std::error_code create_directory(const Twine &path, bool IgnoreExisting,
261 SmallString<128> path_storage;
262 StringRef p = path.toNullTerminatedStringRef(path_storage);
264 if (::mkdir(p.begin(), Perms) == -1) {
265 if (errno != EEXIST || !IgnoreExisting)
266 return std::error_code(errno, std::generic_category());
269 return std::error_code();
272 // Note that we are using symbolic link because hard links are not supported by
273 // all filesystems (SMB doesn't).
274 std::error_code create_link(const Twine &to, const Twine &from) {
276 SmallString<128> from_storage;
277 SmallString<128> to_storage;
278 StringRef f = from.toNullTerminatedStringRef(from_storage);
279 StringRef t = to.toNullTerminatedStringRef(to_storage);
281 if (::symlink(t.begin(), f.begin()) == -1)
282 return std::error_code(errno, std::generic_category());
284 return std::error_code();
287 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
288 SmallString<128> path_storage;
289 StringRef p = path.toNullTerminatedStringRef(path_storage);
292 if (lstat(p.begin(), &buf) != 0) {
293 if (errno != ENOENT || !IgnoreNonExisting)
294 return std::error_code(errno, std::generic_category());
295 return std::error_code();
298 // Note: this check catches strange situations. In all cases, LLVM should
299 // only be involved in the creation and deletion of regular files. This
300 // check ensures that what we're trying to erase is a regular file. It
301 // effectively prevents LLVM from erasing things like /dev/null, any block
302 // special file, or other things that aren't "regular" files.
303 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
304 return make_error_code(errc::operation_not_permitted);
306 if (::remove(p.begin()) == -1) {
307 if (errno != ENOENT || !IgnoreNonExisting)
308 return std::error_code(errno, std::generic_category());
311 return std::error_code();
314 std::error_code rename(const Twine &from, const Twine &to) {
316 SmallString<128> from_storage;
317 SmallString<128> to_storage;
318 StringRef f = from.toNullTerminatedStringRef(from_storage);
319 StringRef t = to.toNullTerminatedStringRef(to_storage);
321 if (::rename(f.begin(), t.begin()) == -1)
322 return std::error_code(errno, std::generic_category());
324 return std::error_code();
327 std::error_code resize_file(int FD, uint64_t Size) {
328 if (::ftruncate(FD, Size) == -1)
329 return std::error_code(errno, std::generic_category());
331 return std::error_code();
334 static int convertAccessMode(AccessMode Mode) {
336 case AccessMode::Exist:
338 case AccessMode::Write:
340 case AccessMode::Execute:
341 return R_OK | X_OK; // scripts also need R_OK.
343 llvm_unreachable("invalid enum");
346 std::error_code access(const Twine &Path, AccessMode Mode) {
347 SmallString<128> PathStorage;
348 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
350 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
351 return std::error_code(errno, std::generic_category());
353 if (Mode == AccessMode::Execute) {
354 // Don't say that directories are executable.
356 if (0 != stat(P.begin(), &buf))
357 return errc::permission_denied;
358 if (!S_ISREG(buf.st_mode))
359 return errc::permission_denied;
362 return std::error_code();
365 bool can_execute(const Twine &Path) {
366 return !access(Path, AccessMode::Execute);
369 bool equivalent(file_status A, file_status B) {
370 assert(status_known(A) && status_known(B));
371 return A.fs_st_dev == B.fs_st_dev &&
372 A.fs_st_ino == B.fs_st_ino;
375 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
376 file_status fsA, fsB;
377 if (std::error_code ec = status(A, fsA))
379 if (std::error_code ec = status(B, fsB))
381 result = equivalent(fsA, fsB);
382 return std::error_code();
385 static std::error_code fillStatus(int StatRet, const struct stat &Status,
386 file_status &Result) {
388 std::error_code ec(errno, std::generic_category());
389 if (ec == errc::no_such_file_or_directory)
390 Result = file_status(file_type::file_not_found);
392 Result = file_status(file_type::status_error);
396 file_type Type = file_type::type_unknown;
398 if (S_ISDIR(Status.st_mode))
399 Type = file_type::directory_file;
400 else if (S_ISREG(Status.st_mode))
401 Type = file_type::regular_file;
402 else if (S_ISBLK(Status.st_mode))
403 Type = file_type::block_file;
404 else if (S_ISCHR(Status.st_mode))
405 Type = file_type::character_file;
406 else if (S_ISFIFO(Status.st_mode))
407 Type = file_type::fifo_file;
408 else if (S_ISSOCK(Status.st_mode))
409 Type = file_type::socket_file;
411 perms Perms = static_cast<perms>(Status.st_mode);
413 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_atime,
414 Status.st_mtime, Status.st_uid, Status.st_gid,
417 return std::error_code();
420 std::error_code status(const Twine &Path, file_status &Result) {
421 SmallString<128> PathStorage;
422 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
425 int StatRet = ::stat(P.begin(), &Status);
426 return fillStatus(StatRet, Status, Result);
429 std::error_code status(int FD, file_status &Result) {
431 int StatRet = ::fstat(FD, &Status);
432 return fillStatus(StatRet, Status, Result);
435 std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
436 #if defined(HAVE_FUTIMENS)
438 Times[0].tv_sec = Time.toEpochTime();
439 Times[0].tv_nsec = 0;
441 if (::futimens(FD, Times))
442 return std::error_code(errno, std::generic_category());
443 return std::error_code();
444 #elif defined(HAVE_FUTIMES)
446 Times[0].tv_sec = Time.toEpochTime();
447 Times[0].tv_usec = 0;
449 if (::futimes(FD, Times))
450 return std::error_code(errno, std::generic_category());
451 return std::error_code();
453 #warning Missing futimes() and futimens()
454 return make_error_code(errc::function_not_supported);
458 std::error_code mapped_file_region::init(int FD, uint64_t Offset,
462 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
463 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
464 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
465 if (Mapping == MAP_FAILED)
466 return std::error_code(errno, std::generic_category());
467 return std::error_code();
470 mapped_file_region::mapped_file_region(int fd, mapmode mode, uint64_t length,
471 uint64_t offset, std::error_code &ec)
472 : Size(length), Mapping() {
473 // Make sure that the requested size fits within SIZE_T.
474 if (length > std::numeric_limits<size_t>::max()) {
475 ec = make_error_code(errc::invalid_argument);
479 ec = init(fd, offset, mode);
484 mapped_file_region::~mapped_file_region() {
486 ::munmap(Mapping, Size);
489 uint64_t mapped_file_region::size() const {
490 assert(Mapping && "Mapping failed but used anyway!");
494 char *mapped_file_region::data() const {
495 assert(Mapping && "Mapping failed but used anyway!");
496 return reinterpret_cast<char*>(Mapping);
499 const char *mapped_file_region::const_data() const {
500 assert(Mapping && "Mapping failed but used anyway!");
501 return reinterpret_cast<const char*>(Mapping);
504 int mapped_file_region::alignment() {
505 return Process::getPageSize();
508 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
510 SmallString<128> path_null(path);
511 DIR *directory = ::opendir(path_null.c_str());
513 return std::error_code(errno, std::generic_category());
515 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
516 // Add something for replace_filename to replace.
517 path::append(path_null, ".");
518 it.CurrentEntry = directory_entry(path_null.str());
519 return directory_iterator_increment(it);
522 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
523 if (it.IterationHandle)
524 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
525 it.IterationHandle = 0;
526 it.CurrentEntry = directory_entry();
527 return std::error_code();
530 std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
532 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
533 if (cur_dir == nullptr && errno != 0) {
534 return std::error_code(errno, std::generic_category());
535 } else if (cur_dir != nullptr) {
536 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
537 if ((name.size() == 1 && name[0] == '.') ||
538 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
539 return directory_iterator_increment(it);
540 it.CurrentEntry.replace_filename(name);
542 return directory_iterator_destruct(it);
544 return std::error_code();
547 std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
548 SmallString<128> Storage;
549 StringRef P = Name.toNullTerminatedStringRef(Storage);
550 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
552 return std::error_code(errno, std::generic_category());
554 return std::error_code();
557 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
558 sys::fs::OpenFlags Flags, unsigned Mode) {
559 // Verify that we don't have both "append" and "excl".
560 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
561 "Cannot specify both 'excl' and 'append' file creation flags!");
563 int OpenFlags = O_CREAT;
568 OpenFlags |= O_WRONLY;
570 if (Flags & F_Append)
571 OpenFlags |= O_APPEND;
573 OpenFlags |= O_TRUNC;
578 SmallString<128> Storage;
579 StringRef P = Name.toNullTerminatedStringRef(Storage);
580 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
582 return std::error_code(errno, std::generic_category());
584 return std::error_code();
587 } // end namespace fs
591 bool home_directory(SmallVectorImpl<char> &result) {
592 if (char *RequestedDir = getenv("HOME")) {
594 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
601 static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
602 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
603 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
604 // macros defined in <unistd.h> on darwin >= 9
605 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR
606 : _CS_DARWIN_USER_CACHE_DIR;
607 size_t ConfLen = confstr(ConfName, nullptr, 0);
610 Result.resize(ConfLen);
611 ConfLen = confstr(ConfName, Result.data(), Result.size());
612 } while (ConfLen > 0 && ConfLen != Result.size());
615 assert(Result.back() == 0);
626 static bool getUserCacheDir(SmallVectorImpl<char> &Result) {
627 // First try using XDG_CACHE_HOME env variable,
628 // as specified in XDG Base Directory Specification at
629 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
630 if (const char *XdgCacheDir = std::getenv("XDG_CACHE_HOME")) {
632 Result.append(XdgCacheDir, XdgCacheDir + strlen(XdgCacheDir));
636 // Try Darwin configuration query
637 if (getDarwinConfDir(false, Result))
640 // Use "$HOME/.cache" if $HOME is available
641 if (home_directory(Result)) {
642 append(Result, ".cache");
649 static const char *getEnvTempDir() {
650 // Check whether the temporary directory is specified by an environment
652 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
653 for (const char *Env : EnvironmentVariables) {
654 if (const char *Dir = std::getenv(Env))
661 static const char *getDefaultTempDir(bool ErasedOnReboot) {
672 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
675 if (ErasedOnReboot) {
676 // There is no env variable for the cache directory.
677 if (const char *RequestedDir = getEnvTempDir()) {
678 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
683 if (getDarwinConfDir(ErasedOnReboot, Result))
686 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
687 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
690 } // end namespace path
692 } // end namespace sys
693 } // end namespace llvm