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 TimeValue file_status::getLastModificationTime() const {
115 Ret.fromEpochTime(fs_st_mtime);
119 error_code current_path(SmallVectorImpl<char> &result) {
121 result.reserve(MAXPATHLEN);
124 result.reserve(1024);
128 if (::getcwd(result.data(), result.capacity()) == 0) {
129 // See if there was a real error.
130 if (errno != errc::not_enough_memory)
131 return error_code(errno, system_category());
132 // Otherwise there just wasn't enough space.
133 result.reserve(result.capacity() * 2);
138 result.set_size(strlen(result.data()));
139 return error_code::success();
142 error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
144 SmallString<128> from_storage;
145 SmallString<128> to_storage;
146 StringRef f = from.toNullTerminatedStringRef(from_storage);
147 StringRef t = to.toNullTerminatedStringRef(to_storage);
149 const size_t buf_sz = 32768;
151 int from_file = -1, to_file = -1;
154 if ((from_file = ::open(f.begin(), O_RDONLY)) < 0)
155 return error_code(errno, system_category());
156 AutoFD from_fd(from_file);
159 struct stat from_stat;
160 if (::stat(f.begin(), &from_stat) != 0)
161 return error_code(errno, system_category());
164 int to_flags = O_CREAT | O_WRONLY;
165 if (copt == copy_option::fail_if_exists)
169 if ((to_file = ::open(t.begin(), to_flags, from_stat.st_mode)) < 0)
170 return error_code(errno, system_category());
171 AutoFD to_fd(to_file);
174 ssize_t sz, sz_read = 1, sz_write;
175 while (sz_read > 0 &&
176 (sz_read = ::read(from_fd, buffer, buf_sz)) > 0) {
177 // Allow for partial writes - see Advanced Unix Programming (2nd Ed.),
178 // Marc Rochkind, Addison-Wesley, 2004, page 94
181 if ((sz = ::write(to_fd, buffer + sz_write, sz_read - sz_write)) < 0) {
182 sz_read = sz; // cause read loop termination.
186 } while (sz_write < sz_read);
189 // After all the file operations above the return value of close actually
191 if (::close(from_fd.take()) < 0) sz_read = -1;
192 if (::close(to_fd.take()) < 0) sz_read = -1;
196 return error_code(errno, system_category());
198 return error_code::success();
201 error_code create_directory(const Twine &path, bool &existed) {
202 SmallString<128> path_storage;
203 StringRef p = path.toNullTerminatedStringRef(path_storage);
205 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) {
206 if (errno != errc::file_exists)
207 return error_code(errno, system_category());
212 return error_code::success();
215 error_code create_hard_link(const Twine &to, const Twine &from) {
217 SmallString<128> from_storage;
218 SmallString<128> to_storage;
219 StringRef f = from.toNullTerminatedStringRef(from_storage);
220 StringRef t = to.toNullTerminatedStringRef(to_storage);
222 if (::link(t.begin(), f.begin()) == -1)
223 return error_code(errno, system_category());
225 return error_code::success();
228 error_code create_symlink(const Twine &to, const Twine &from) {
230 SmallString<128> from_storage;
231 SmallString<128> to_storage;
232 StringRef f = from.toNullTerminatedStringRef(from_storage);
233 StringRef t = to.toNullTerminatedStringRef(to_storage);
235 if (::symlink(t.begin(), f.begin()) == -1)
236 return error_code(errno, system_category());
238 return error_code::success();
241 error_code remove(const Twine &path, bool &existed) {
242 SmallString<128> path_storage;
243 StringRef p = path.toNullTerminatedStringRef(path_storage);
246 if (stat(p.begin(), &buf) != 0) {
247 if (errno != errc::no_such_file_or_directory)
248 return error_code(errno, system_category());
250 return error_code::success();
253 // Note: this check catches strange situations. In all cases, LLVM should
254 // only be involved in the creation and deletion of regular files. This
255 // check ensures that what we're trying to erase is a regular file. It
256 // effectively prevents LLVM from erasing things like /dev/null, any block
257 // special file, or other things that aren't "regular" files.
258 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode))
259 return make_error_code(errc::operation_not_permitted);
261 if (::remove(p.begin()) == -1) {
262 if (errno != errc::no_such_file_or_directory)
263 return error_code(errno, system_category());
268 return error_code::success();
271 error_code rename(const Twine &from, const Twine &to) {
273 SmallString<128> from_storage;
274 SmallString<128> to_storage;
275 StringRef f = from.toNullTerminatedStringRef(from_storage);
276 StringRef t = to.toNullTerminatedStringRef(to_storage);
278 if (::rename(f.begin(), t.begin()) == -1) {
279 // If it's a cross device link, copy then delete, otherwise return the error
280 if (errno == EXDEV) {
281 if (error_code ec = copy_file(from, to, copy_option::overwrite_if_exists))
284 if (error_code ec = remove(from, Existed))
287 return error_code(errno, system_category());
290 return error_code::success();
293 error_code resize_file(const Twine &path, uint64_t size) {
294 SmallString<128> path_storage;
295 StringRef p = path.toNullTerminatedStringRef(path_storage);
297 if (::truncate(p.begin(), size) == -1)
298 return error_code(errno, system_category());
300 return error_code::success();
303 error_code exists(const Twine &path, bool &result) {
304 SmallString<128> path_storage;
305 StringRef p = path.toNullTerminatedStringRef(path_storage);
307 if (::access(p.begin(), F_OK) == -1) {
308 if (errno != errc::no_such_file_or_directory)
309 return error_code(errno, system_category());
314 return error_code::success();
317 bool can_write(const Twine &Path) {
318 SmallString<128> PathStorage;
319 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
320 return 0 == access(P.begin(), W_OK);
323 bool can_execute(const Twine &Path) {
324 SmallString<128> PathStorage;
325 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
327 if (0 != access(P.begin(), R_OK | X_OK))
330 if (0 != stat(P.begin(), &buf))
332 if (!S_ISREG(buf.st_mode))
337 bool equivalent(file_status A, file_status B) {
338 assert(status_known(A) && status_known(B));
339 return A.fs_st_dev == B.fs_st_dev &&
340 A.fs_st_ino == B.fs_st_ino;
343 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
344 file_status fsA, fsB;
345 if (error_code ec = status(A, fsA)) return ec;
346 if (error_code ec = status(B, fsB)) return ec;
347 result = equivalent(fsA, fsB);
348 return error_code::success();
351 error_code file_size(const Twine &path, uint64_t &result) {
352 SmallString<128> path_storage;
353 StringRef p = path.toNullTerminatedStringRef(path_storage);
356 if (::stat(p.begin(), &status) == -1)
357 return error_code(errno, system_category());
358 if (!S_ISREG(status.st_mode))
359 return make_error_code(errc::operation_not_permitted);
361 result = status.st_size;
362 return error_code::success();
365 error_code getUniqueID(const Twine Path, uint64_t &Result) {
366 SmallString<128> Storage;
367 StringRef P = Path.toNullTerminatedStringRef(Storage);
370 if (::stat(P.begin(), &Status) != 0)
371 return error_code(errno, system_category());
373 Result = Status.st_ino;
374 return error_code::success();
377 error_code status(const Twine &path, file_status &result) {
378 SmallString<128> path_storage;
379 StringRef p = path.toNullTerminatedStringRef(path_storage);
382 if (::stat(p.begin(), &status) != 0) {
383 error_code ec(errno, system_category());
384 if (ec == errc::no_such_file_or_directory)
385 result = file_status(file_type::file_not_found);
387 result = file_status(file_type::status_error);
391 perms prms = static_cast<perms>(status.st_mode & perms_mask);
393 if (S_ISDIR(status.st_mode))
394 result = file_status(file_type::directory_file, prms);
395 else if (S_ISREG(status.st_mode))
396 result = file_status(file_type::regular_file, prms);
397 else if (S_ISBLK(status.st_mode))
398 result = file_status(file_type::block_file, prms);
399 else if (S_ISCHR(status.st_mode))
400 result = file_status(file_type::character_file, prms);
401 else if (S_ISFIFO(status.st_mode))
402 result = file_status(file_type::fifo_file, prms);
403 else if (S_ISSOCK(status.st_mode))
404 result = file_status(file_type::socket_file, prms);
406 result = file_status(file_type::type_unknown, prms);
408 result.fs_st_dev = status.st_dev;
409 result.fs_st_ino = status.st_ino;
410 result.fs_st_mtime = status.st_mtime;
412 return error_code::success();
415 // Modifies permissions on a file.
416 error_code permissions(const Twine &path, perms prms) {
417 if ((prms & add_perms) && (prms & remove_perms))
418 llvm_unreachable("add_perms and remove_perms are mutually exclusive");
420 // Get current permissions
422 if (error_code ec = status(path, info)) {
426 // Set updated permissions.
427 SmallString<128> path_storage;
428 StringRef p = path.toNullTerminatedStringRef(path_storage);
430 if (prms & add_perms) {
431 permsToSet = (info.permissions() | prms) & perms_mask;
432 } else if (prms & remove_perms) {
433 permsToSet = (info.permissions() & ~prms) & perms_mask;
435 permsToSet = prms & perms_mask;
437 if (::chmod(p.begin(), static_cast<mode_t>(permsToSet))) {
438 return error_code(errno, system_category());
441 return error_code::success();
444 error_code setLastModificationAndAccessTime(int FD, TimeValue Time) {
446 Times[0].tv_sec = Time.toPosixTime();
447 Times[0].tv_usec = 0;
449 if (::futimes(FD, Times))
450 return error_code(errno, system_category());
451 return error_code::success();
454 // Since this is most often used for temporary files, mode defaults to 0600.
455 error_code unique_file(const Twine &model, int &result_fd,
456 SmallVectorImpl<char> &result_path,
457 bool makeAbsolute, unsigned mode) {
458 SmallString<128> Model;
459 model.toVector(Model);
464 // Make model absolute by prepending a temp directory if it's not already.
465 bool absolute = path::is_absolute(Twine(Model));
467 SmallString<128> TDir;
468 if (error_code ec = TempDir(TDir)) return ec;
469 path::append(TDir, Twine(Model));
474 // From here on, DO NOT modify model. It may be needed if the randomly chosen
475 // path already exists.
476 SmallString<128> RandomPath = Model;
479 // Replace '%' with random chars.
480 for (unsigned i = 0, e = Model.size(); i != e; ++i) {
482 RandomPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
485 // Make sure we don't fall into an infinite loop by constantly trying
486 // to create the parent path.
487 bool TriedToCreateParent = false;
489 // Try to open + create the file.
491 int RandomFD = ::open(RandomPath.c_str(), O_RDWR | O_CREAT | O_EXCL, mode);
492 if (RandomFD == -1) {
493 int SavedErrno = errno;
494 // If the file existed, try again, otherwise, error.
495 if (SavedErrno == errc::file_exists)
496 goto retry_random_path;
497 // If path prefix doesn't exist, try to create it.
498 if (SavedErrno == errc::no_such_file_or_directory && !TriedToCreateParent) {
499 TriedToCreateParent = true;
500 StringRef p(RandomPath);
501 SmallString<64> dir_to_create;
502 for (path::const_iterator i = path::begin(p),
503 e = --path::end(p); i != e; ++i) {
504 path::append(dir_to_create, *i);
506 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
508 // Don't try to create network paths.
509 if (i->size() > 2 && (*i)[0] == '/' &&
512 return make_error_code(errc::no_such_file_or_directory);
513 if (::mkdir(dir_to_create.c_str(), 0700) == -1 &&
514 errno != errc::file_exists)
515 return error_code(errno, system_category());
518 goto rety_open_create;
521 return error_code(SavedErrno, system_category());
524 // Make the path absolute.
525 char real_path_buff[PATH_MAX + 1];
526 if (realpath(RandomPath.c_str(), real_path_buff) == NULL) {
529 ::unlink(RandomPath.c_str());
530 return error_code(error, system_category());
534 StringRef d(real_path_buff);
535 result_path.append(d.begin(), d.end());
537 result_fd = RandomFD;
538 return error_code::success();
541 error_code mapped_file_region::init(int FD, bool CloseFD, uint64_t Offset) {
546 // Figure out how large the file is.
547 struct stat FileInfo;
548 if (fstat(FD, &FileInfo) == -1)
549 return error_code(errno, system_category());
550 uint64_t FileSize = FileInfo.st_size;
554 else if (FileSize < Size) {
555 // We need to grow the file.
556 if (ftruncate(FD, Size) == -1)
557 return error_code(errno, system_category());
560 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
561 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
565 Mapping = ::mmap(0, Size, prot, flags, FD, Offset);
566 if (Mapping == MAP_FAILED)
567 return error_code(errno, system_category());
568 return error_code::success();
571 mapped_file_region::mapped_file_region(const Twine &path,
579 // Make sure that the requested size fits within SIZE_T.
580 if (length > std::numeric_limits<size_t>::max()) {
581 ec = make_error_code(errc::invalid_argument);
585 SmallString<128> path_storage;
586 StringRef name = path.toNullTerminatedStringRef(path_storage);
587 int oflags = (mode == readonly) ? O_RDONLY : O_RDWR;
588 int ofd = ::open(name.begin(), oflags);
590 ec = error_code(errno, system_category());
594 ec = init(ofd, true, offset);
599 mapped_file_region::mapped_file_region(int fd,
608 // Make sure that the requested size fits within SIZE_T.
609 if (length > std::numeric_limits<size_t>::max()) {
610 ec = make_error_code(errc::invalid_argument);
614 ec = init(fd, closefd, offset);
619 mapped_file_region::~mapped_file_region() {
621 ::munmap(Mapping, Size);
624 #if LLVM_HAS_RVALUE_REFERENCES
625 mapped_file_region::mapped_file_region(mapped_file_region &&other)
626 : Mode(other.Mode), Size(other.Size), Mapping(other.Mapping) {
631 mapped_file_region::mapmode mapped_file_region::flags() const {
632 assert(Mapping && "Mapping failed but used anyway!");
636 uint64_t mapped_file_region::size() const {
637 assert(Mapping && "Mapping failed but used anyway!");
641 char *mapped_file_region::data() const {
642 assert(Mapping && "Mapping failed but used anyway!");
643 assert(Mode != readonly && "Cannot get non const data for readonly mapping!");
644 return reinterpret_cast<char*>(Mapping);
647 const char *mapped_file_region::const_data() const {
648 assert(Mapping && "Mapping failed but used anyway!");
649 return reinterpret_cast<const char*>(Mapping);
652 int mapped_file_region::alignment() {
653 return process::get_self()->page_size();
656 error_code detail::directory_iterator_construct(detail::DirIterState &it,
658 SmallString<128> path_null(path);
659 DIR *directory = ::opendir(path_null.c_str());
661 return error_code(errno, system_category());
663 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
664 // Add something for replace_filename to replace.
665 path::append(path_null, ".");
666 it.CurrentEntry = directory_entry(path_null.str());
667 return directory_iterator_increment(it);
670 error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
671 if (it.IterationHandle)
672 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
673 it.IterationHandle = 0;
674 it.CurrentEntry = directory_entry();
675 return error_code::success();
678 error_code detail::directory_iterator_increment(detail::DirIterState &it) {
680 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle));
681 if (cur_dir == 0 && errno != 0) {
682 return error_code(errno, system_category());
683 } else if (cur_dir != 0) {
684 StringRef name(cur_dir->d_name, NAMLEN(cur_dir));
685 if ((name.size() == 1 && name[0] == '.') ||
686 (name.size() == 2 && name[0] == '.' && name[1] == '.'))
687 return directory_iterator_increment(it);
688 it.CurrentEntry.replace_filename(name);
690 return directory_iterator_destruct(it);
692 return error_code::success();
695 error_code get_magic(const Twine &path, uint32_t len,
696 SmallVectorImpl<char> &result) {
697 SmallString<128> PathStorage;
698 StringRef Path = path.toNullTerminatedStringRef(PathStorage);
702 std::FILE *file = std::fopen(Path.data(), "rb");
704 return error_code(errno, system_category());
710 size_t size = std::fread(result.data(), 1, len, file);
711 if (std::ferror(file) != 0) {
713 return error_code(errno, system_category());
714 } else if (size != len) {
715 if (std::feof(file) != 0) {
717 result.set_size(size);
718 return make_error_code(errc::value_too_large);
722 result.set_size(size);
723 return error_code::success();
726 error_code map_file_pages(const Twine &path, off_t file_offset, size_t size,
727 bool map_writable, void *&result) {
728 SmallString<128> path_storage;
729 StringRef name = path.toNullTerminatedStringRef(path_storage);
730 int oflags = map_writable ? O_RDWR : O_RDONLY;
731 int ofd = ::open(name.begin(), oflags);
733 return error_code(errno, system_category());
735 int flags = map_writable ? MAP_SHARED : MAP_PRIVATE;
736 int prot = map_writable ? (PROT_READ|PROT_WRITE) : PROT_READ;
740 result = ::mmap(0, size, prot, flags, fd, file_offset);
741 if (result == MAP_FAILED) {
742 return error_code(errno, system_category());
745 return error_code::success();
748 error_code unmap_file_pages(void *base, size_t size) {
749 if ( ::munmap(base, size) == -1 )
750 return error_code(errno, system_category());
752 return error_code::success();
756 } // end namespace fs
757 } // end namespace sys
758 } // end namespace llvm