1 //===- llvm/Support/Unix/PathV2.cpp - 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 PathV2 API.
12 //===----------------------------------------------------------------------===//
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic UNIX code that
16 //=== is guaranteed to work on *all* UNIX variants.
17 //===----------------------------------------------------------------------===//
20 #include "llvm/Support/Process.h"
27 #ifdef HAVE_SYS_MMAN_H
32 # define NAMLEN(dirent) strlen((dirent)->d_name)
34 # define dirent direct
35 # define NAMLEN(dirent) (dirent)->d_namlen
37 # include <sys/ndir.h>
53 // Both stdio.h and cstdio are included via different pathes and
54 // stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
60 #if defined(__GNU__) && !defined(PATH_MAX)
61 # define PATH_MAX 4096
67 /// This class automatically closes the given file descriptor when it goes out
68 /// of scope. You can take back explicit ownership of the file descriptor by
69 /// calling take(). The destructor does not verify that close was successful.
70 /// Therefore, never allow this class to call close on a file descriptor that
71 /// has been read from or written to.
75 AutoFD(int fd) : FileDescriptor(fd) {}
77 if (FileDescriptor >= 0)
78 ::close(FileDescriptor);
82 int ret = FileDescriptor;
87 operator int() const {return FileDescriptor;}
90 error_code TempDir(SmallVectorImpl<char> &result) {
91 // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
93 (dir = std::getenv("TMPDIR" )) ||
94 (dir = std::getenv("TMP" )) ||
95 (dir = std::getenv("TEMP" )) ||
96 (dir = std::getenv("TEMPDIR")) ||
104 result.append(d.begin(), d.end());
105 return error_code::success();
113 error_code current_path(SmallVectorImpl<char> &result) {
115 result.reserve(MAXPATHLEN);
118 result.reserve(1024);
122 if (::getcwd(result.data(), result.capacity()) == 0) {
123 // See if there was a real error.
124 if (errno != errc::not_enough_memory)
125 return error_code(errno, system_category());
126 // Otherwise there just wasn't enough space.
127 result.reserve(result.capacity() * 2);
132 result.set_size(strlen(result.data()));
133 return error_code::success();
136 error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
138 SmallString<128> from_storage;
139 SmallString<128> to_storage;
140 StringRef f = from.toNullTerminatedStringRef(from_storage);
141 StringRef t = to.toNullTerminatedStringRef(to_storage);
143 const size_t buf_sz = 32768;
145 int from_file = -1, to_file = -1;
148 if ((from_file = ::open(f.begin(), O_RDONLY)) < 0)
149 return error_code(errno, system_category());
150 AutoFD from_fd(from_file);
153 struct stat from_stat;
154 if (::stat(f.begin(), &from_stat) != 0)
155 return error_code(errno, system_category());
158 int to_flags = O_CREAT | O_WRONLY;
159 if (copt == copy_option::fail_if_exists)
163 if ((to_file = ::open(t.begin(), to_flags, from_stat.st_mode)) < 0)
164 return error_code(errno, system_category());
165 AutoFD to_fd(to_file);
168 ssize_t sz, sz_read = 1, sz_write;
169 while (sz_read > 0 &&
170 (sz_read = ::read(from_fd, buffer, buf_sz)) > 0) {
171 // Allow for partial writes - see Advanced Unix Programming (2nd Ed.),
172 // Marc Rochkind, Addison-Wesley, 2004, page 94
175 if ((sz = ::write(to_fd, buffer + sz_write, sz_read - sz_write)) < 0) {
176 sz_read = sz; // cause read loop termination.
180 } while (sz_write < sz_read);
183 // After all the file operations above the return value of close actually
185 if (::close(from_fd.take()) < 0) sz_read = -1;
186 if (::close(to_fd.take()) < 0) sz_read = -1;
190 return error_code(errno, system_category());
192 return error_code::success();
195 error_code create_directory(const Twine &path, bool &existed) {
196 SmallString<128> path_storage;
197 StringRef p = path.toNullTerminatedStringRef(path_storage);
199 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
200 if (errno != errc::file_exists)
201 return error_code(errno, system_category());
206 return error_code::success();
209 error_code create_hard_link(const Twine &to, const Twine &from) {
211 SmallString<128> from_storage;
212 SmallString<128> to_storage;
213 StringRef f = from.toNullTerminatedStringRef(from_storage);
214 StringRef t = to.toNullTerminatedStringRef(to_storage);
216 if (::link(t.begin(), f.begin()) == -1)
217 return error_code(errno, system_category());
219 return error_code::success();
222 error_code create_symlink(const Twine &to, const Twine &from) {
224 SmallString<128> from_storage;
225 SmallString<128> to_storage;
226 StringRef f = from.toNullTerminatedStringRef(from_storage);
227 StringRef t = to.toNullTerminatedStringRef(to_storage);
229 if (::symlink(t.begin(), f.begin()) == -1)
230 return error_code(errno, system_category());
232 return error_code::success();
235 error_code remove(const Twine &path, bool &existed) {
236 SmallString<128> path_storage;
237 StringRef p = path.toNullTerminatedStringRef(path_storage);
240 if (stat(p.begin(), &buf) != 0) {
241 if (errno != errc::no_such_file_or_directory)
242 return error_code(errno, system_category());
244 return error_code::success();
247 // Note: this check catches strange situations. In all cases, LLVM should
248 // only be involved in the creation and deletion of regular files. This
249 // check ensures that what we're trying to erase is a regular file. It
250 // effectively prevents LLVM from erasing things like /dev/null, any block
251 // special file, or other things that aren't "regular" files.
252 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
253 return make_error_code(errc::operation_not_permitted);
255 if (::remove(p.begin()) == -1) {
256 if (errno != errc::no_such_file_or_directory)
257 return error_code(errno, system_category());
262 return error_code::success();
265 error_code rename(const Twine &from, const Twine &to) {
267 SmallString<128> from_storage;
268 SmallString<128> to_storage;
269 StringRef f = from.toNullTerminatedStringRef(from_storage);
270 StringRef t = to.toNullTerminatedStringRef(to_storage);
272 if (::rename(f.begin(), t.begin()) == -1) {
273 // If it's a cross device link, copy then delete, otherwise return the error
274 if (errno == EXDEV) {
275 if (error_code ec = copy_file(from, to, copy_option::overwrite_if_exists))
278 if (error_code ec = remove(from, Existed))
281 return error_code(errno, system_category());
284 return error_code::success();
287 error_code resize_file(const Twine &path, uint64_t size) {
288 SmallString<128> path_storage;
289 StringRef p = path.toNullTerminatedStringRef(path_storage);
291 if (::truncate(p.begin(), size) == -1)
292 return error_code(errno, system_category());
294 return error_code::success();
297 error_code exists(const Twine &path, bool &result) {
298 SmallString<128> path_storage;
299 StringRef p = path.toNullTerminatedStringRef(path_storage);
301 if (::access(p.begin(), F_OK) == -1) {
302 if (errno != errc::no_such_file_or_directory)
303 return error_code(errno, system_category());
308 return error_code::success();
311 bool can_execute(const Twine &Path) {
312 SmallString<128> PathStorage;
313 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
315 if (0 != access(P.begin(), R_OK | X_OK))
318 if (0 != stat(P.begin(), &buf))
320 if (!S_ISREG(buf.st_mode))
325 bool equivalent(file_status A, file_status B) {
326 assert(status_known(A) && status_known(B));
327 return A.fs_st_dev == B.fs_st_dev &&
328 A.fs_st_ino == B.fs_st_ino;
331 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
332 file_status fsA, fsB;
333 if (error_code ec = status(A, fsA)) return ec;
334 if (error_code ec = status(B, fsB)) return ec;
335 result = equivalent(fsA, fsB);
336 return error_code::success();
339 error_code file_size(const Twine &path, uint64_t &result) {
340 SmallString<128> path_storage;
341 StringRef p = path.toNullTerminatedStringRef(path_storage);
344 if (::stat(p.begin(), &status) == -1)
345 return error_code(errno, system_category());
346 if (!S_ISREG(status.st_mode))
347 return make_error_code(errc::operation_not_permitted);
349 result = status.st_size;
350 return error_code::success();
353 error_code GetUniqueID(const Twine Path, uint64_t &Result) {
354 SmallString<128> Storage;
355 StringRef P = Path.toNullTerminatedStringRef(Storage);
358 if (::stat(P.begin(), &Status) != 0)
359 return error_code(errno, system_category());
361 Result = Status.st_ino;
362 return error_code::success();
365 error_code status(const Twine &path, file_status &result) {
366 SmallString<128> path_storage;
367 StringRef p = path.toNullTerminatedStringRef(path_storage);
370 if (::stat(p.begin(), &status) != 0) {
371 error_code ec(errno, system_category());
372 if (ec == errc::no_such_file_or_directory)
373 result = file_status(file_type::file_not_found);
375 result = file_status(file_type::status_error);
379 perms prms = static_cast<perms>(status.st_mode & perms_mask);
381 if (S_ISDIR(status.st_mode))
382 result = file_status(file_type::directory_file, prms);
383 else if (S_ISREG(status.st_mode))
384 result = file_status(file_type::regular_file, prms);
385 else if (S_ISBLK(status.st_mode))
386 result = file_status(file_type::block_file, prms);
387 else if (S_ISCHR(status.st_mode))
388 result = file_status(file_type::character_file, prms);
389 else if (S_ISFIFO(status.st_mode))
390 result = file_status(file_type::fifo_file, prms);
391 else if (S_ISSOCK(status.st_mode))
392 result = file_status(file_type::socket_file, prms);
394 result = file_status(file_type::type_unknown, prms);
396 result.fs_st_dev = status.st_dev;
397 result.fs_st_ino = status.st_ino;
399 return error_code::success();
402 // Modifies permissions on a file.
403 error_code permissions(const Twine &path, perms prms) {
404 if ((prms & add_perms) && (prms & remove_perms))
405 llvm_unreachable("add_perms and remove_perms are mutually exclusive");
407 // Get current permissions
409 if (error_code ec = status(path, info)) {
413 // Set updated permissions.
414 SmallString<128> path_storage;
415 StringRef p = path.toNullTerminatedStringRef(path_storage);
417 if (prms & add_perms) {
418 permsToSet = (info.permissions() | prms) & perms_mask;
419 } else if (prms & remove_perms) {
420 permsToSet = (info.permissions() & ~prms) & perms_mask;
422 permsToSet = prms & perms_mask;
424 if (::chmod(p.begin(), static_cast<mode_t>(permsToSet))) {
425 return error_code(errno, system_category());
428 return error_code::success();
431 // Since this is most often used for temporary files, mode defaults to 0600.
432 error_code unique_file(const Twine &model, int &result_fd,
433 SmallVectorImpl<char> &result_path,
434 bool makeAbsolute, unsigned mode) {
435 SmallString<128> Model;
436 model.toVector(Model);
441 // Make model absolute by prepending a temp directory if it's not already.
442 bool absolute = path::is_absolute(Twine(Model));
444 SmallString<128> TDir;
445 if (error_code ec = TempDir(TDir)) return ec;
446 path::append(TDir, Twine(Model));
451 // From here on, DO NOT modify model. It may be needed if the randomly chosen
452 // path already exists.
453 SmallString<128> RandomPath = Model;
456 // Replace '%' with random chars.
457 for (unsigned i = 0, e = Model.size(); i != e; ++i) {
459 RandomPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
462 // Make sure we don't fall into an infinite loop by constantly trying
463 // to create the parent path.
464 bool TriedToCreateParent = false;
466 // Try to open + create the file.
468 int RandomFD = ::open(RandomPath.c_str(), O_RDWR | O_CREAT | O_EXCL, mode);
469 if (RandomFD == -1) {
470 int SavedErrno = errno;
471 // If the file existed, try again, otherwise, error.
472 if (SavedErrno == errc::file_exists)
473 goto retry_random_path;
474 // If path prefix doesn't exist, try to create it.
475 if (SavedErrno == errc::no_such_file_or_directory && !TriedToCreateParent) {
476 TriedToCreateParent = true;
477 StringRef p(RandomPath);
478 SmallString<64> dir_to_create;
479 for (path::const_iterator i = path::begin(p),
480 e = --path::end(p); i != e; ++i) {
481 path::append(dir_to_create, *i);
483 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
485 // Don't try to create network paths.
486 if (i->size() > 2 && (*i)[0] == '/' &&
489 return make_error_code(errc::no_such_file_or_directory);
490 if (::mkdir(dir_to_create.c_str(), 0700) == -1 &&
491 errno != errc::file_exists)
492 return error_code(errno, system_category());
495 goto rety_open_create;
498 return error_code(SavedErrno, system_category());
501 // Make the path absolute.
502 char real_path_buff[PATH_MAX + 1];
503 if (realpath(RandomPath.c_str(), real_path_buff) == NULL) {
506 ::unlink(RandomPath.c_str());
507 return error_code(error, system_category());
511 StringRef d(real_path_buff);
512 result_path.append(d.begin(), d.end());
514 result_fd = RandomFD;
515 return error_code::success();
518 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
523 // Figure out how large the file is.
524 struct stat FileInfo;
525 if (fstat(FD, &FileInfo) == -1)
526 return error_code(errno, system_category());
527 uint64_t FileSize = FileInfo.st_size;
531 else if (FileSize < Size) {
532 // We need to grow the file.
533 if (ftruncate(FD, Size) == -1)
534 return error_code(errno, system_category());
537 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
538 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
542 Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
543 if (Mapping == MAP_FAILED)
544 return error_code(errno, system_category());
545 return error_code::success();
548 mapped_file_region::mapped_file_region(const Twine &path,
556 // Make sure that the requested size fits within SIZE_T.
557 if (length > std::numeric_limits<size_t>::max()) {
558 ec = make_error_code(errc::invalid_argument);
562 SmallString<128> path_storage;
563 StringRef name = path.toNullTerminatedStringRef(path_storage);
564 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
565 int ofd = ::open(name.begin(), oflags);
567 ec = error_code(errno, system_category());
571 ec = init(ofd, true, offset);
576 mapped_file_region::mapped_file_region(int fd,
585 // Make sure that the requested size fits within SIZE_T.
586 if (length > std::numeric_limits<size_t>::max()) {
587 ec = make_error_code(errc::invalid_argument);
591 ec = init(fd, closefd, offset);
596 mapped_file_region::~mapped_file_region() {
598 ::munmap(Mapping, Size);
601 #if LLVM_HAS_RVALUE_REFERENCES
602 mapped_file_region::mapped_file_region(mapped_file_region &&other)
603 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
608 mapped_file_region::mapmode mapped_file_region::flags() const {
609 assert(Mapping && "Mapping failed but used anyway!");
613 uint64_t mapped_file_region::size() const {
614 assert(Mapping && "Mapping failed but used anyway!");
618 char *mapped_file_region::data() const {
619 assert(Mapping && "Mapping failed but used anyway!");
620 assert(Mode != readonly && "Cannot get non const data for readonly mapping!");
621 return reinterpret_cast<char*>(Mapping);
624 const char *mapped_file_region::const_data() const {
625 assert(Mapping && "Mapping failed but used anyway!");
626 return reinterpret_cast<const char*>(Mapping);
629 int mapped_file_region::alignment() {
630 return process::get_self()->page_size();
633 error_code detail::directory_iterator_construct(detail::DirIterState &it,
635 SmallString<128> path_null(path);
636 DIR *directory = ::opendir(path_null.c_str());
638 return error_code(errno, system_category());
640 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
641 // Add something for replace_filename to replace.
642 path::append(path_null, ".");
643 it.CurrentEntry = directory_entry(path_null.str());
644 return directory_iterator_increment(it);
647 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
648 if (it.IterationHandle)
649 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
650 it.IterationHandle = 0;
651 it.CurrentEntry = directory_entry();
652 return error_code::success();
655 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
657 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
658 if (cur_dir == 0 && errno != 0) {
659 return error_code(errno, system_category());
660 } else if (cur_dir != 0) {
661 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
662 if ((name.size() == 1 && name[0] == '.') ||
663 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
664 return directory_iterator_increment(it);
665 it.CurrentEntry.replace_filename(name);
667 return directory_iterator_destruct(it);
669 return error_code::success();
672 error_code get_magic(const Twine &path, uint32_t len,
673 SmallVectorImpl<char> &result) {
674 SmallString<128> PathStorage;
675 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
679 std::FILE *file = std::fopen(Path.data(), "rb");
681 return error_code(errno, system_category());
687 size_t size = std::fread(result.data(), 1, len, file);
688 if (std::ferror(file) != 0) {
690 return error_code(errno, system_category());
691 } else if (size != result.size()) {
692 if (std::feof(file) != 0) {
694 result.set_size(size);
695 return make_error_code(errc::value_too_large);
699 result.set_size(len);
700 return error_code::success();
703 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
704 bool map_writable, void *&result) {
705 SmallString<128> path_storage;
706 StringRef name = path.toNullTerminatedStringRef(path_storage);
707 int oflags = map_writable ? O_RDWR : O_RDONLY;
708 int ofd = ::open(name.begin(), oflags);
710 return error_code(errno, system_category());
712 int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
713 int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
717 result = ::mmap(0, size, prot, flags, fd, file_offset);
718 if (result == MAP_FAILED) {
719 return error_code(errno, system_category());
722 return error_code::success();
725 error_code unmap_file_pages(void *base, size_t size) {
726 if ( ::munmap(base, size) == -1 )
727 return error_code(errno, system_category());
729 return error_code::success();
733 } // end namespace fs
734 } // end namespace sys
735 } // end namespace llvm