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;}
93 #if defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
94 defined(__OpenBSD__) || defined(__minix) || defined(__FreeBSD_kernel__) || \
95 defined(__linux__) || defined(__CYGWIN__) || defined(__DragonFly__)
97 test_dir(char ret[PATH_MAX], const char *dir, const char *bin)
100 char fullpath[PATH_MAX];
102 snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
103 if (realpath(fullpath, ret) == NULL)
105 if (stat(fullpath, &sb) != 0)
112 getprogpath(char ret[PATH_MAX], const char *bin)
116 /* First approach: absolute path. */
118 if (test_dir(ret, "/", bin) == 0)
123 /* Second approach: relative path. */
124 if (strchr(bin, '/') != NULL) {
126 if (getcwd(cwd, PATH_MAX) == NULL)
128 if (test_dir(ret, cwd, bin) == 0)
133 /* Third approach: $PATH */
134 if ((pv = getenv("PATH")) == NULL)
139 while ((t = strsep(&s, ":")) != NULL) {
140 if (test_dir(ret, t, bin) == 0) {
148 #endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
150 /// GetMainExecutable - Return the path to the main executable, given the
151 /// value of argv[0] from program startup.
152 std::string getMainExecutable(const char *argv0, void *MainAddr) {
153 #if defined(__APPLE__)
154 // On OS X the executable path is saved to the stack by dyld. Reading it
155 // from there is much faster than calling dladdr, especially for large
156 // binaries with symbols.
157 char exe_path[MAXPATHLEN];
158 uint32_t size = sizeof(exe_path);
159 if (_NSGetExecutablePath(exe_path, &size) == 0) {
160 char link_path[MAXPATHLEN];
161 if (realpath(exe_path, link_path))
164 #elif defined(__FreeBSD__) || defined (__NetBSD__) || defined(__Bitrig__) || \
165 defined(__OpenBSD__) || defined(__minix) || defined(__DragonFly__) || \
166 defined(__FreeBSD_kernel__)
167 char exe_path[PATH_MAX];
169 if (getprogpath(exe_path, argv0) != NULL)
171 #elif defined(__linux__) || defined(__CYGWIN__)
172 char exe_path[MAXPATHLEN];
173 StringRef aPath("/proc/self/exe");
174 if (sys::fs::exists(aPath)) {
175 // /proc is not always mounted under Linux (chroot for example).
176 ssize_t len = readlink(aPath.str().c_str(), exe_path, sizeof(exe_path));
178 return StringRef(exe_path, len);
180 // Fall back to the classical detection.
181 if (getprogpath(exe_path, argv0) != NULL)
184 #elif defined(HAVE_DLFCN_H)
185 // Use dladdr to get executable path if available.
187 int err = dladdr(MainAddr, &DLInfo);
191 // If the filename is a symlink, we need to resolve and return the location of
192 // the actual executable.
193 char link_path[MAXPATHLEN];
194 if (realpath(DLInfo.dli_fname, link_path))
197 #error GetMainExecutable is not implemented on this host yet.
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 std::error_code current_path(SmallVectorImpl<char> &result) {
215 const char *pwd = ::getenv("PWD");
216 llvm::sys::fs::file_status PWDStatus, DotStatus;
217 if (pwd && llvm::sys::path::is_absolute(pwd) &&
218 !llvm::sys::fs::status(pwd, PWDStatus) &&
219 !llvm::sys::fs::status(".", DotStatus) &&
220 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
221 result.append(pwd, pwd + strlen(pwd));
222 return std::error_code();
226 result.reserve(MAXPATHLEN);
229 result.reserve(1024);
233 if (::getcwd(result.data(), result.capacity()) == nullptr) {
234 // See if there was a real error.
236 return std::error_code(errno, std::generic_category());
237 // Otherwise there just wasn't enough space.
238 result.reserve(result.capacity() * 2);
243 result.set_size(strlen(result.data()));
244 return std::error_code();
247 std::error_code create_directory(const Twine &path, bool IgnoreExisting) {
248 SmallString<128> path_storage;
249 StringRef p = path.toNullTerminatedStringRef(path_storage);
251 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
252 if (errno != EEXIST || !IgnoreExisting)
253 return std::error_code(errno, std::generic_category());
256 return std::error_code();
259 // Note that we are using symbolic link because hard links are not supported by
260 // all filesystems (SMB doesn't).
261 std::error_code create_link(const Twine &to, const Twine &from) {
263 SmallString<128> from_storage;
264 SmallString<128> to_storage;
265 StringRef f = from.toNullTerminatedStringRef(from_storage);
266 StringRef t = to.toNullTerminatedStringRef(to_storage);
268 if (::symlink(t.begin(), f.begin()) == -1)
269 return std::error_code(errno, std::generic_category());
271 return std::error_code();
274 std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
275 SmallString<128> path_storage;
276 StringRef p = path.toNullTerminatedStringRef(path_storage);
279 if (lstat(p.begin(), &buf) != 0) {
280 if (errno != ENOENT || !IgnoreNonExisting)
281 return std::error_code(errno, std::generic_category());
282 return std::error_code();
285 // Note: this check catches strange situations. In all cases, LLVM should
286 // only be involved in the creation and deletion of regular files. This
287 // check ensures that what we're trying to erase is a regular file. It
288 // effectively prevents LLVM from erasing things like /dev/null, any block
289 // special file, or other things that aren't "regular" files.
290 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
291 return make_error_code(errc::operation_not_permitted);
293 if (::remove(p.begin()) == -1) {
294 if (errno != ENOENT || !IgnoreNonExisting)
295 return std::error_code(errno, std::generic_category());
298 return std::error_code();
301 std::error_code rename(const Twine &from, const Twine &to) {
303 SmallString<128> from_storage;
304 SmallString<128> to_storage;
305 StringRef f = from.toNullTerminatedStringRef(from_storage);
306 StringRef t = to.toNullTerminatedStringRef(to_storage);
308 if (::rename(f.begin(), t.begin()) == -1)
309 return std::error_code(errno, std::generic_category());
311 return std::error_code();
314 std::error_code resize_file(const Twine &path, uint64_t size) {
315 SmallString<128> path_storage;
316 StringRef p = path.toNullTerminatedStringRef(path_storage);
318 if (::truncate(p.begin(), size) == -1)
319 return std::error_code(errno, std::generic_category());
321 return std::error_code();
324 std::error_code exists(const Twine &path, bool &result) {
325 SmallString<128> path_storage;
326 StringRef p = path.toNullTerminatedStringRef(path_storage);
328 if (::access(p.begin(), F_OK) == -1) {
330 return std::error_code(errno, std::generic_category());
335 return std::error_code();
338 bool can_write(const Twine &Path) {
339 SmallString<128> PathStorage;
340 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
341 return 0 == access(P.begin(), W_OK);
344 bool can_execute(const Twine &Path) {
345 SmallString<128> PathStorage;
346 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
348 if (0 != access(P.begin(), R_OK | X_OK))
351 if (0 != stat(P.begin(), &buf))
353 if (!S_ISREG(buf.st_mode))
358 bool equivalent(file_status A, file_status B) {
359 assert(status_known(A) && status_known(B));
360 return A.fs_st_dev == B.fs_st_dev &&
361 A.fs_st_ino == B.fs_st_ino;
364 std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
365 file_status fsA, fsB;
366 if (std::error_code ec = status(A, fsA))
368 if (std::error_code ec = status(B, fsB))
370 result = equivalent(fsA, fsB);
371 return std::error_code();
374 static std::error_code fillStatus(int StatRet, const struct stat &Status,
375 file_status &Result) {
377 std::error_code ec(errno, std::generic_category());
378 if (ec == errc::no_such_file_or_directory)
379 Result = file_status(file_type::file_not_found);
381 Result = file_status(file_type::status_error);
385 file_type Type = file_type::type_unknown;
387 if (S_ISDIR(Status.st_mode))
388 Type = file_type::directory_file;
389 else if (S_ISREG(Status.st_mode))
390 Type = file_type::regular_file;
391 else if (S_ISBLK(Status.st_mode))
392 Type = file_type::block_file;
393 else if (S_ISCHR(Status.st_mode))
394 Type = file_type::character_file;
395 else if (S_ISFIFO(Status.st_mode))
396 Type = file_type::fifo_file;
397 else if (S_ISSOCK(Status.st_mode))
398 Type = file_type::socket_file;
400 perms Perms = static_cast<perms>(Status.st_mode);
402 file_status(Type, Perms, Status.st_dev, Status.st_ino, Status.st_mtime,
403 Status.st_uid, Status.st_gid, Status.st_size);
405 return std::error_code();
408 std::error_code status(const Twine &Path, file_status &Result) {
409 SmallString<128> PathStorage;
410 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
413 int StatRet = ::stat(P.begin(), &Status);
414 return fillStatus(StatRet, Status, Result);
417 std::error_code status(int FD, file_status &Result) {
419 int StatRet = ::fstat(FD, &Status);
420 return fillStatus(StatRet, Status, Result);
423 std::error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
424 #if defined(HAVE_FUTIMENS)
426 Times[0].tv_sec = Time.toEpochTime();
427 Times[0].tv_nsec = 0;
429 if (::futimens(FD, Times))
430 return std::error_code(errno, std::generic_category());
431 return std::error_code();
432 #elif defined(HAVE_FUTIMES)
434 Times[0].tv_sec = Time.toEpochTime();
435 Times[0].tv_usec = 0;
437 if (::futimes(FD, Times))
438 return std::error_code(errno, std::generic_category());
439 return std::error_code();
441 #warning Missing futimes() and futimens()
442 return make_error_code(errc::function_not_supported);
446 std::error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
451 // Figure out how large the file is.
452 struct stat FileInfo;
453 if (fstat(FD, &FileInfo) == -1)
454 return std::error_code(errno, std::generic_category());
455 uint64_t FileSize = FileInfo.st_size;
459 else if (FileSize < Size) {
460 // We need to grow the file.
461 if (ftruncate(FD, Size) == -1)
462 return std::error_code(errno, std::generic_category());
465 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
466 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
470 Mapping = ::mmap(nullptr, Size, prot, flags, FD, Offset);
471 if (Mapping == MAP_FAILED)
472 return std::error_code(errno, std::generic_category());
473 return std::error_code();
476 mapped_file_region::mapped_file_region(const Twine &path,
484 // Make sure that the requested size fits within SIZE_T.
485 if (length > std::numeric_limits<size_t>::max()) {
486 ec = make_error_code(errc::invalid_argument);
490 SmallString<128> path_storage;
491 StringRef name = path.toNullTerminatedStringRef(path_storage);
492 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
493 int ofd = ::open(name.begin(), oflags);
495 ec = std::error_code(errno, std::generic_category());
499 ec = init(ofd, true, offset);
504 mapped_file_region::mapped_file_region(int fd,
513 // Make sure that the requested size fits within SIZE_T.
514 if (length > std::numeric_limits<size_t>::max()) {
515 ec = make_error_code(errc::invalid_argument);
519 ec = init(fd, closefd, offset);
524 mapped_file_region::~mapped_file_region() {
526 ::munmap(Mapping, Size);
529 mapped_file_region::mapped_file_region(mapped_file_region &&other)
530 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
531 other.Mapping = nullptr;
534 mapped_file_region::mapmode mapped_file_region::flags() const {
535 assert(Mapping && "Mapping failed but used anyway!");
539 uint64_t mapped_file_region::size() const {
540 assert(Mapping && "Mapping failed but used anyway!");
544 char *mapped_file_region::data() const {
545 assert(Mapping && "Mapping failed but used anyway!");
546 assert(Mode != readonly && "Cannot get non-const data for readonly mapping!");
547 return reinterpret_cast<char*>(Mapping);
550 const char *mapped_file_region::const_data() const {
551 assert(Mapping && "Mapping failed but used anyway!");
552 return reinterpret_cast<const char*>(Mapping);
555 int mapped_file_region::alignment() {
556 return process::get_self()->page_size();
559 std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
561 SmallString<128> path_null(path);
562 DIR *directory = ::opendir(path_null.c_str());
564 return std::error_code(errno, std::generic_category());
566 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
567 // Add something for replace_filename to replace.
568 path::append(path_null, ".");
569 it.CurrentEntry = directory_entry(path_null.str());
570 return directory_iterator_increment(it);
573 std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
574 if (it.IterationHandle)
575 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
576 it.IterationHandle = 0;
577 it.CurrentEntry = directory_entry();
578 return std::error_code();
581 std::error_code detail::directory_iterator_increment(detail::DirIterState &it) {
583 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
584 if (cur_dir == nullptr && errno != 0) {
585 return std::error_code(errno, std::generic_category());
586 } else if (cur_dir != nullptr) {
587 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
588 if ((name.size() == 1 && name[0] == '.') ||
589 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
590 return directory_iterator_increment(it);
591 it.CurrentEntry.replace_filename(name);
593 return directory_iterator_destruct(it);
595 return std::error_code();
598 std::error_code openFileForRead(const Twine &Name, int &ResultFD) {
599 SmallString<128> Storage;
600 StringRef P = Name.toNullTerminatedStringRef(Storage);
601 while ((ResultFD = open(P.begin(), O_RDONLY)) < 0) {
603 return std::error_code(errno, std::generic_category());
605 return std::error_code();
608 std::error_code openFileForWrite(const Twine &Name, int &ResultFD,
609 sys::fs::OpenFlags Flags, unsigned Mode) {
610 // Verify that we don't have both "append" and "excl".
611 assert((!(Flags & sys::fs::F_Excl) || !(Flags & sys::fs::F_Append)) &&
612 "Cannot specify both 'excl' and 'append' file creation flags!");
614 int OpenFlags = O_CREAT;
619 OpenFlags |= O_WRONLY;
621 if (Flags & F_Append)
622 OpenFlags |= O_APPEND;
624 OpenFlags |= O_TRUNC;
629 SmallString<128> Storage;
630 StringRef P = Name.toNullTerminatedStringRef(Storage);
631 while ((ResultFD = open(P.begin(), OpenFlags, Mode)) < 0) {
633 return std::error_code(errno, std::generic_category());
635 return std::error_code();
638 } // end namespace fs
642 bool home_directory(SmallVectorImpl<char> &result) {
643 if (char *RequestedDir = getenv("HOME")) {
645 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
652 static const char *getEnvTempDir() {
653 // Check whether the temporary directory is specified by an environment
655 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
656 for (const char *Env : EnvironmentVariables) {
657 if (const char *Dir = std::getenv(Env))
664 static const char *getDefaultTempDir(bool ErasedOnReboot) {
675 void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
678 if (ErasedOnReboot) {
679 // There is no env variable for the cache directory.
680 if (const char *RequestedDir = getEnvTempDir()) {
681 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
686 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
687 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
688 // macros defined in <unistd.h> on darwin >= 9
689 int ConfName = ErasedOnReboot? _CS_DARWIN_USER_TEMP_DIR
690 : _CS_DARWIN_USER_CACHE_DIR;
691 size_t ConfLen = confstr(ConfName, nullptr, 0);
694 Result.resize(ConfLen);
695 ConfLen = confstr(ConfName, Result.data(), Result.size());
696 } while (ConfLen > 0 && ConfLen != Result.size());
699 assert(Result.back() == 0);
708 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
709 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
712 } // end namespace path
714 } // end namespace sys
715 } // end namespace llvm