1 //===-- Path.cpp - Implement OS Path Concept ------------------------------===//
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 operating system Path API.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/Path.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/Support/Endian.h"
17 #include "llvm/Support/Errc.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Process.h"
21 #include "llvm/Support/Signals.h"
25 #if !defined(_MSC_VER) && !defined(__MINGW32__)
32 using namespace llvm::support::endian;
35 using llvm::StringRef;
36 using llvm::sys::path::is_separator;
37 using llvm::sys::path::Style;
39 inline Style real_style(Style style) {
41 return (style == Style::posix) ? Style::posix : Style::windows;
43 return (style == Style::windows) ? Style::windows : Style::posix;
47 inline const char *separators(Style style) {
48 if (real_style(style) == Style::windows)
53 inline char preferred_separator(Style style) {
54 if (real_style(style) == Style::windows)
59 StringRef find_first_component(StringRef path, Style style) {
60 // Look for this first component in the following order.
61 // * empty (in this case we return an empty string)
62 // * either C: or {//,\\}net.
64 // * {file,directory}name
69 if (real_style(style) == Style::windows) {
71 if (path.size() >= 2 &&
72 std::isalpha(static_cast<unsigned char>(path[0])) && path[1] == ':')
73 return path.substr(0, 2);
77 if ((path.size() > 2) && is_separator(path[0], style) &&
78 path[0] == path[1] && !is_separator(path[2], style)) {
79 // Find the next directory separator.
80 size_t end = path.find_first_of(separators(style), 2);
81 return path.substr(0, end);
85 if (is_separator(path[0], style))
86 return path.substr(0, 1);
88 // * {file,directory}name
89 size_t end = path.find_first_of(separators(style));
90 return path.substr(0, end);
93 size_t filename_pos(StringRef str, Style style) {
94 if (str.size() == 2 && is_separator(str[0], style) && str[0] == str[1])
97 if (str.size() > 0 && is_separator(str[str.size() - 1], style))
98 return str.size() - 1;
100 size_t pos = str.find_last_of(separators(style), str.size() - 1);
102 if (real_style(style) == Style::windows) {
103 if (pos == StringRef::npos)
104 pos = str.find_last_of(':', str.size() - 2);
107 if (pos == StringRef::npos || (pos == 1 && is_separator(str[0], style)))
113 size_t root_dir_start(StringRef str, Style style) {
115 if (real_style(style) == Style::windows) {
116 if (str.size() > 2 && str[1] == ':' && is_separator(str[2], style))
121 if (str.size() == 2 && is_separator(str[0], style) && str[0] == str[1])
122 return StringRef::npos;
125 if (str.size() > 3 && is_separator(str[0], style) && str[0] == str[1] &&
126 !is_separator(str[2], style)) {
127 return str.find_first_of(separators(style), 2);
131 if (str.size() > 0 && is_separator(str[0], style))
134 return StringRef::npos;
137 size_t parent_path_end(StringRef path, Style style) {
138 size_t end_pos = filename_pos(path, style);
140 bool filename_was_sep =
141 path.size() > 0 && is_separator(path[end_pos], style);
143 // Skip separators except for root dir.
144 size_t root_dir_pos = root_dir_start(path.substr(0, end_pos), style);
146 while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
147 is_separator(path[end_pos - 1], style))
150 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
151 return StringRef::npos;
155 } // end unnamed namespace
163 static std::error_code
164 createUniqueEntity(const Twine &Model, int &ResultFD,
165 SmallVectorImpl<char> &ResultPath, bool MakeAbsolute,
166 unsigned Mode, FSEntity Type,
167 sys::fs::OpenFlags Flags = sys::fs::F_None) {
168 SmallString<128> ModelStorage;
169 Model.toVector(ModelStorage);
172 // Make model absolute by prepending a temp directory if it's not already.
173 if (!sys::path::is_absolute(Twine(ModelStorage))) {
174 SmallString<128> TDir;
175 sys::path::system_temp_directory(true, TDir);
176 sys::path::append(TDir, Twine(ModelStorage));
177 ModelStorage.swap(TDir);
181 // From here on, DO NOT modify model. It may be needed if the randomly chosen
182 // path already exists.
183 ResultPath = ModelStorage;
185 ResultPath.push_back(0);
186 ResultPath.pop_back();
189 // Replace '%' with random chars.
190 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
191 if (ModelStorage[i] == '%')
192 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
195 // Try to open + create the file.
198 if (std::error_code EC =
199 sys::fs::openFileForWrite(Twine(ResultPath.begin()), ResultFD,
200 Flags | sys::fs::F_Excl, Mode)) {
201 if (EC == errc::file_exists)
202 goto retry_random_path;
206 return std::error_code();
211 sys::fs::access(ResultPath.begin(), sys::fs::AccessMode::Exist);
212 if (EC == errc::no_such_file_or_directory)
213 return std::error_code();
216 goto retry_random_path;
220 if (std::error_code EC =
221 sys::fs::create_directory(ResultPath.begin(), false)) {
222 if (EC == errc::file_exists)
223 goto retry_random_path;
226 return std::error_code();
229 llvm_unreachable("Invalid Type");
236 const_iterator begin(StringRef path, Style style) {
239 i.Component = find_first_component(path, style);
245 const_iterator end(StringRef path) {
248 i.Position = path.size();
252 const_iterator &const_iterator::operator++() {
253 assert(Position < Path.size() && "Tried to increment past end!");
255 // Increment Position to past the current component
256 Position += Component.size();
259 if (Position == Path.size()) {
260 Component = StringRef();
264 // Both POSIX and Windows treat paths that begin with exactly two separators
266 bool was_net = Component.size() > 2 && is_separator(Component[0], S) &&
267 Component[1] == Component[0] && !is_separator(Component[2], S);
269 // Handle separators.
270 if (is_separator(Path[Position], S)) {
274 (real_style(S) == Style::windows && Component.endswith(":"))) {
275 Component = Path.substr(Position, 1);
279 // Skip extra separators.
280 while (Position != Path.size() && is_separator(Path[Position], S)) {
284 // Treat trailing '/' as a '.'.
285 if (Position == Path.size()) {
292 // Find next component.
293 size_t end_pos = Path.find_first_of(separators(S), Position);
294 Component = Path.slice(Position, end_pos);
299 bool const_iterator::operator==(const const_iterator &RHS) const {
300 return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
303 ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
304 return Position - RHS.Position;
307 reverse_iterator rbegin(StringRef Path, Style style) {
310 I.Position = Path.size();
315 reverse_iterator rend(StringRef Path) {
318 I.Component = Path.substr(0, 0);
323 reverse_iterator &reverse_iterator::operator++() {
324 // If we're at the end and the previous char was a '/', return '.' unless
325 // we are the root path.
326 size_t root_dir_pos = root_dir_start(Path, S);
327 if (Position == Path.size() && Path.size() > root_dir_pos + 1 &&
328 is_separator(Path[Position - 1], S)) {
334 // Skip separators unless it's the root directory.
335 size_t end_pos = Position;
337 while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
338 is_separator(Path[end_pos - 1], S))
341 // Find next separator.
342 size_t start_pos = filename_pos(Path.substr(0, end_pos), S);
343 Component = Path.slice(start_pos, end_pos);
344 Position = start_pos;
348 bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
349 return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
350 Position == RHS.Position;
353 ptrdiff_t reverse_iterator::operator-(const reverse_iterator &RHS) const {
354 return Position - RHS.Position;
357 StringRef root_path(StringRef path, Style style) {
358 const_iterator b = begin(path, style), pos = b, e = end(path);
361 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
362 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
364 if (has_net || has_drive) {
365 if ((++pos != e) && is_separator((*pos)[0], style)) {
366 // {C:/,//net/}, so get the first two components.
367 return path.substr(0, b->size() + pos->size());
369 // just {C:,//net}, return the first component.
374 // POSIX style root directory.
375 if (is_separator((*b)[0], style)) {
383 StringRef root_name(StringRef path, Style style) {
384 const_iterator b = begin(path, style), e = end(path);
387 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
388 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
390 if (has_net || has_drive) {
391 // just {C:,//net}, return the first component.
396 // No path or no name.
400 StringRef root_directory(StringRef path, Style style) {
401 const_iterator b = begin(path, style), pos = b, e = end(path);
404 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
405 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
407 if ((has_net || has_drive) &&
408 // {C:,//net}, skip to the next component.
409 (++pos != e) && is_separator((*pos)[0], style)) {
413 // POSIX style root directory.
414 if (!has_net && is_separator((*b)[0], style)) {
419 // No path or no root.
423 StringRef relative_path(StringRef path, Style style) {
424 StringRef root = root_path(path, style);
425 return path.substr(root.size());
428 void append(SmallVectorImpl<char> &path, Style style, const Twine &a,
429 const Twine &b, const Twine &c, const Twine &d) {
430 SmallString<32> a_storage;
431 SmallString<32> b_storage;
432 SmallString<32> c_storage;
433 SmallString<32> d_storage;
435 SmallVector<StringRef, 4> components;
436 if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
437 if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
438 if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
439 if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
441 for (auto &component : components) {
443 !path.empty() && is_separator(path[path.size() - 1], style);
445 // Strip separators from beginning of component.
446 size_t loc = component.find_first_not_of(separators(style));
447 StringRef c = component.substr(loc);
450 path.append(c.begin(), c.end());
454 bool component_has_sep =
455 !component.empty() && is_separator(component[0], style);
456 if (!component_has_sep &&
457 !(path.empty() || has_root_name(component, style))) {
459 path.push_back(preferred_separator(style));
462 path.append(component.begin(), component.end());
466 void append(SmallVectorImpl<char> &path, const Twine &a, const Twine &b,
467 const Twine &c, const Twine &d) {
468 append(path, Style::native, a, b, c, d);
471 void append(SmallVectorImpl<char> &path, const_iterator begin,
472 const_iterator end, Style style) {
473 for (; begin != end; ++begin)
474 path::append(path, style, *begin);
477 StringRef parent_path(StringRef path, Style style) {
478 size_t end_pos = parent_path_end(path, style);
479 if (end_pos == StringRef::npos)
482 return path.substr(0, end_pos);
485 void remove_filename(SmallVectorImpl<char> &path, Style style) {
486 size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()), style);
487 if (end_pos != StringRef::npos)
488 path.set_size(end_pos);
491 void replace_extension(SmallVectorImpl<char> &path, const Twine &extension,
493 StringRef p(path.begin(), path.size());
494 SmallString<32> ext_storage;
495 StringRef ext = extension.toStringRef(ext_storage);
497 // Erase existing extension.
498 size_t pos = p.find_last_of('.');
499 if (pos != StringRef::npos && pos >= filename_pos(p, style))
502 // Append '.' if needed.
503 if (ext.size() > 0 && ext[0] != '.')
507 path.append(ext.begin(), ext.end());
510 void replace_path_prefix(SmallVectorImpl<char> &Path,
511 const StringRef &OldPrefix, const StringRef &NewPrefix,
513 if (OldPrefix.empty() && NewPrefix.empty())
516 StringRef OrigPath(Path.begin(), Path.size());
517 if (!OrigPath.startswith(OldPrefix))
520 // If prefixes have the same size we can simply copy the new one over.
521 if (OldPrefix.size() == NewPrefix.size()) {
522 std::copy(NewPrefix.begin(), NewPrefix.end(), Path.begin());
526 StringRef RelPath = OrigPath.substr(OldPrefix.size());
527 SmallString<256> NewPath;
528 path::append(NewPath, style, NewPrefix);
529 path::append(NewPath, style, RelPath);
533 void native(const Twine &path, SmallVectorImpl<char> &result, Style style) {
534 assert((!path.isSingleStringRef() ||
535 path.getSingleStringRef().data() != result.data()) &&
536 "path and result are not allowed to overlap!");
539 path.toVector(result);
540 native(result, style);
543 void native(SmallVectorImpl<char> &Path, Style style) {
546 if (real_style(style) == Style::windows) {
547 std::replace(Path.begin(), Path.end(), '/', '\\');
548 if (Path[0] == '~' && (Path.size() == 1 || is_separator(Path[1], style))) {
549 SmallString<128> PathHome;
550 home_directory(PathHome);
551 PathHome.append(Path.begin() + 1, Path.end());
555 for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
558 if (PN < PE && *PN == '\\')
559 ++PI; // increment once, the for loop will move over the escaped slash
567 std::string convert_to_slash(StringRef path, Style style) {
568 if (real_style(style) != Style::windows)
571 std::string s = path.str();
572 std::replace(s.begin(), s.end(), '\\', '/');
576 StringRef filename(StringRef path, Style style) { return *rbegin(path, style); }
578 StringRef stem(StringRef path, Style style) {
579 StringRef fname = filename(path, style);
580 size_t pos = fname.find_last_of('.');
581 if (pos == StringRef::npos)
584 if ((fname.size() == 1 && fname == ".") ||
585 (fname.size() == 2 && fname == ".."))
588 return fname.substr(0, pos);
591 StringRef extension(StringRef path, Style style) {
592 StringRef fname = filename(path, style);
593 size_t pos = fname.find_last_of('.');
594 if (pos == StringRef::npos)
597 if ((fname.size() == 1 && fname == ".") ||
598 (fname.size() == 2 && fname == ".."))
601 return fname.substr(pos);
604 bool is_separator(char value, Style style) {
607 if (real_style(style) == Style::windows)
608 return value == '\\';
612 StringRef get_separator(Style style) {
613 if (real_style(style) == Style::windows)
618 bool has_root_name(const Twine &path, Style style) {
619 SmallString<128> path_storage;
620 StringRef p = path.toStringRef(path_storage);
622 return !root_name(p, style).empty();
625 bool has_root_directory(const Twine &path, Style style) {
626 SmallString<128> path_storage;
627 StringRef p = path.toStringRef(path_storage);
629 return !root_directory(p, style).empty();
632 bool has_root_path(const Twine &path, Style style) {
633 SmallString<128> path_storage;
634 StringRef p = path.toStringRef(path_storage);
636 return !root_path(p, style).empty();
639 bool has_relative_path(const Twine &path, Style style) {
640 SmallString<128> path_storage;
641 StringRef p = path.toStringRef(path_storage);
643 return !relative_path(p, style).empty();
646 bool has_filename(const Twine &path, Style style) {
647 SmallString<128> path_storage;
648 StringRef p = path.toStringRef(path_storage);
650 return !filename(p, style).empty();
653 bool has_parent_path(const Twine &path, Style style) {
654 SmallString<128> path_storage;
655 StringRef p = path.toStringRef(path_storage);
657 return !parent_path(p, style).empty();
660 bool has_stem(const Twine &path, Style style) {
661 SmallString<128> path_storage;
662 StringRef p = path.toStringRef(path_storage);
664 return !stem(p, style).empty();
667 bool has_extension(const Twine &path, Style style) {
668 SmallString<128> path_storage;
669 StringRef p = path.toStringRef(path_storage);
671 return !extension(p, style).empty();
674 bool is_absolute(const Twine &path, Style style) {
675 SmallString<128> path_storage;
676 StringRef p = path.toStringRef(path_storage);
678 bool rootDir = has_root_directory(p, style);
680 (real_style(style) != Style::windows) || has_root_name(p, style);
682 return rootDir && rootName;
685 bool is_relative(const Twine &path, Style style) {
686 return !is_absolute(path, style);
689 StringRef remove_leading_dotslash(StringRef Path, Style style) {
690 // Remove leading "./" (or ".//" or "././" etc.)
691 while (Path.size() > 2 && Path[0] == '.' && is_separator(Path[1], style)) {
692 Path = Path.substr(2);
693 while (Path.size() > 0 && is_separator(Path[0], style))
694 Path = Path.substr(1);
699 static SmallString<256> remove_dots(StringRef path, bool remove_dot_dot,
701 SmallVector<StringRef, 16> components;
703 // Skip the root path, then look for traversal in the components.
704 StringRef rel = path::relative_path(path, style);
706 llvm::make_range(path::begin(rel, style), path::end(rel))) {
709 // Leading ".." will remain in the path unless it's at the root.
710 if (remove_dot_dot && C == "..") {
711 if (!components.empty() && components.back() != "..") {
712 components.pop_back();
715 if (path::is_absolute(path, style))
718 components.push_back(C);
721 SmallString<256> buffer = path::root_path(path, style);
722 for (StringRef C : components)
723 path::append(buffer, style, C);
727 bool remove_dots(SmallVectorImpl<char> &path, bool remove_dot_dot,
729 StringRef p(path.data(), path.size());
731 SmallString<256> result = remove_dots(p, remove_dot_dot, style);
739 } // end namespace path
743 std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
745 std::error_code EC = status(Path, Status);
748 Result = Status.getUniqueID();
749 return std::error_code();
752 std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
753 SmallVectorImpl<char> &ResultPath,
754 unsigned Mode, sys::fs::OpenFlags Flags) {
755 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File,
759 std::error_code createUniqueFile(const Twine &Model,
760 SmallVectorImpl<char> &ResultPath) {
762 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
765 static std::error_code
766 createTemporaryFile(const Twine &Model, int &ResultFD,
767 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type,
768 sys::fs::OpenFlags Flags) {
769 SmallString<128> Storage;
770 StringRef P = Model.toNullTerminatedStringRef(Storage);
771 assert(P.find_first_of(separators(Style::native)) == StringRef::npos &&
772 "Model must be a simple filename.");
773 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
774 return createUniqueEntity(P.begin(), ResultFD, ResultPath, true,
775 owner_read | owner_write, Type, Flags);
778 static std::error_code
779 createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
780 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type,
781 sys::fs::OpenFlags Flags = sys::fs::F_None) {
782 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
783 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
787 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
789 SmallVectorImpl<char> &ResultPath,
790 sys::fs::OpenFlags Flags) {
791 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File,
795 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
796 SmallVectorImpl<char> &ResultPath) {
798 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
802 // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
803 // for consistency. We should try using mkdtemp.
804 std::error_code createUniqueDirectory(const Twine &Prefix,
805 SmallVectorImpl<char> &ResultPath) {
807 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
811 static std::error_code make_absolute(const Twine ¤t_directory,
812 SmallVectorImpl<char> &path,
813 bool use_current_directory) {
814 StringRef p(path.data(), path.size());
816 bool rootDirectory = path::has_root_directory(p);
818 (real_style(Style::native) != Style::windows) || path::has_root_name(p);
821 if (rootName && rootDirectory)
822 return std::error_code();
824 // All of the following conditions will need the current directory.
825 SmallString<128> current_dir;
826 if (use_current_directory)
827 current_directory.toVector(current_dir);
828 else if (std::error_code ec = current_path(current_dir))
831 // Relative path. Prepend the current directory.
832 if (!rootName && !rootDirectory) {
833 // Append path to the current directory.
834 path::append(current_dir, p);
835 // Set path to the result.
836 path.swap(current_dir);
837 return std::error_code();
840 if (!rootName && rootDirectory) {
841 StringRef cdrn = path::root_name(current_dir);
842 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
843 path::append(curDirRootName, p);
844 // Set path to the result.
845 path.swap(curDirRootName);
846 return std::error_code();
849 if (rootName && !rootDirectory) {
850 StringRef pRootName = path::root_name(p);
851 StringRef bRootDirectory = path::root_directory(current_dir);
852 StringRef bRelativePath = path::relative_path(current_dir);
853 StringRef pRelativePath = path::relative_path(p);
855 SmallString<128> res;
856 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
858 return std::error_code();
861 llvm_unreachable("All rootName and rootDirectory combinations should have "
865 std::error_code make_absolute(const Twine ¤t_directory,
866 SmallVectorImpl<char> &path) {
867 return make_absolute(current_directory, path, true);
870 std::error_code make_absolute(SmallVectorImpl<char> &path) {
871 return make_absolute(Twine(), path, false);
874 std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
876 SmallString<128> PathStorage;
877 StringRef P = Path.toStringRef(PathStorage);
879 // Be optimistic and try to create the directory
880 std::error_code EC = create_directory(P, IgnoreExisting, Perms);
881 // If we succeeded, or had any error other than the parent not existing, just
883 if (EC != errc::no_such_file_or_directory)
886 // We failed because of a no_such_file_or_directory, try to create the
888 StringRef Parent = path::parent_path(P);
892 if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
895 return create_directory(P, IgnoreExisting, Perms);
898 std::error_code copy_file(const Twine &From, const Twine &To) {
900 if (std::error_code EC = openFileForRead(From, ReadFD))
902 if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
907 const size_t BufSize = 4096;
908 char *Buf = new char[BufSize];
909 int BytesRead = 0, BytesWritten = 0;
911 BytesRead = read(ReadFD, Buf, BufSize);
915 BytesWritten = write(WriteFD, Buf, BytesRead);
916 if (BytesWritten < 0)
918 BytesRead -= BytesWritten;
920 if (BytesWritten < 0)
927 if (BytesRead < 0 || BytesWritten < 0)
928 return std::error_code(errno, std::generic_category());
929 return std::error_code();
932 ErrorOr<MD5::MD5Result> md5_contents(int FD) {
935 constexpr size_t BufSize = 4096;
936 std::vector<uint8_t> Buf(BufSize);
939 BytesRead = read(FD, Buf.data(), BufSize);
942 Hash.update(makeArrayRef(Buf.data(), BytesRead));
946 return std::error_code(errno, std::generic_category());
947 MD5::MD5Result Result;
952 ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path) {
954 if (auto EC = openFileForRead(Path, FD))
957 auto Result = md5_contents(FD);
962 bool exists(const basic_file_status &status) {
963 return status_known(status) && status.type() != file_type::file_not_found;
966 bool status_known(const basic_file_status &s) {
967 return s.type() != file_type::status_error;
970 file_type get_file_type(const Twine &Path, bool Follow) {
972 if (status(Path, st, Follow))
973 return file_type::status_error;
977 bool is_directory(const basic_file_status &status) {
978 return status.type() == file_type::directory_file;
981 std::error_code is_directory(const Twine &path, bool &result) {
983 if (std::error_code ec = status(path, st))
985 result = is_directory(st);
986 return std::error_code();
989 bool is_regular_file(const basic_file_status &status) {
990 return status.type() == file_type::regular_file;
993 std::error_code is_regular_file(const Twine &path, bool &result) {
995 if (std::error_code ec = status(path, st))
997 result = is_regular_file(st);
998 return std::error_code();
1001 bool is_symlink_file(const basic_file_status &status) {
1002 return status.type() == file_type::symlink_file;
1005 std::error_code is_symlink_file(const Twine &path, bool &result) {
1007 if (std::error_code ec = status(path, st, false))
1009 result = is_symlink_file(st);
1010 return std::error_code();
1013 bool is_other(const basic_file_status &status) {
1014 return exists(status) &&
1015 !is_regular_file(status) &&
1016 !is_directory(status);
1019 std::error_code is_other(const Twine &Path, bool &Result) {
1020 file_status FileStatus;
1021 if (std::error_code EC = status(Path, FileStatus))
1023 Result = is_other(FileStatus);
1024 return std::error_code();
1027 void directory_entry::replace_filename(const Twine &filename,
1028 basic_file_status st) {
1029 SmallString<128> path = path::parent_path(Path);
1030 path::append(path, filename);
1035 ErrorOr<perms> getPermissions(const Twine &Path) {
1037 if (std::error_code EC = status(Path, Status))
1040 return Status.permissions();
1043 } // end namespace fs
1044 } // end namespace sys
1045 } // end namespace llvm
1047 // Include the truly platform-specific parts.
1048 #if defined(LLVM_ON_UNIX)
1049 #include "Unix/Path.inc"
1051 #if defined(LLVM_ON_WIN32)
1052 #include "Windows/Path.inc"
1058 TempFile::TempFile(StringRef Name, int FD) : TmpName(Name), FD(FD) {}
1059 TempFile::TempFile(TempFile &&Other) { *this = std::move(Other); }
1060 TempFile &TempFile::operator=(TempFile &&Other) {
1061 TmpName = std::move(Other.TmpName);
1067 TempFile::~TempFile() { assert(Done); }
1069 Error TempFile::discard() {
1071 std::error_code RemoveEC;
1072 // On windows closing will remove the file.
1073 #ifndef LLVM_ON_WIN32
1074 // Always try to close and remove.
1075 if (!TmpName.empty()) {
1076 RemoveEC = fs::remove(TmpName);
1077 sys::DontRemoveFileOnSignal(TmpName);
1084 if (FD != -1 && close(FD) == -1) {
1085 std::error_code EC = std::error_code(errno, std::generic_category());
1086 return errorCodeToError(EC);
1090 return errorCodeToError(RemoveEC);
1093 Error TempFile::keep(const Twine &Name) {
1096 // Always try to close and rename.
1097 #ifdef LLVM_ON_WIN32
1098 // If we cant't cancel the delete don't rename.
1099 std::error_code RenameEC = cancelDeleteOnClose(FD);
1101 RenameEC = rename_fd(FD, Name);
1102 // If we can't rename, discard the temporary file.
1106 std::error_code RenameEC = fs::rename(TmpName, Name);
1107 // If we can't rename, discard the temporary file.
1110 sys::DontRemoveFileOnSignal(TmpName);
1116 if (close(FD) == -1) {
1117 std::error_code EC(errno, std::generic_category());
1118 return errorCodeToError(EC);
1122 return errorCodeToError(RenameEC);
1125 Error TempFile::keep() {
1129 #ifdef LLVM_ON_WIN32
1130 if (std::error_code EC = cancelDeleteOnClose(FD))
1131 return errorCodeToError(EC);
1133 sys::DontRemoveFileOnSignal(TmpName);
1138 if (close(FD) == -1) {
1139 std::error_code EC(errno, std::generic_category());
1140 return errorCodeToError(EC);
1144 return Error::success();
1147 Expected<TempFile> TempFile::create(const Twine &Model, unsigned Mode) {
1149 SmallString<128> ResultPath;
1150 if (std::error_code EC = createUniqueFile(Model, FD, ResultPath, Mode,
1151 sys::fs::F_RW | sys::fs::F_Delete))
1152 return errorCodeToError(EC);
1154 TempFile Ret(ResultPath, FD);
1155 #ifndef LLVM_ON_WIN32
1156 if (sys::RemoveFileOnSignal(ResultPath)) {
1157 // Make sure we delete the file when RemoveFileOnSignal fails.
1158 consumeError(Ret.discard());
1159 std::error_code EC(errc::operation_not_permitted);
1160 return errorCodeToError(EC);
1163 return std::move(Ret);
1169 bool user_cache_directory(SmallVectorImpl<char> &Result, const Twine &Path1,
1170 const Twine &Path2, const Twine &Path3) {
1171 if (getUserCacheDir(Result)) {
1172 append(Result, Path1, Path2, Path3);
1178 } // end namespace path
1179 } // end namsspace sys
1180 } // end namespace llvm