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/Config/llvm-config.h"
17 #include "llvm/Support/Endian.h"
18 #include "llvm/Support/Errc.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/Process.h"
22 #include "llvm/Support/Signals.h"
26 #if !defined(_MSC_VER) && !defined(__MINGW32__)
33 using namespace llvm::support::endian;
36 using llvm::StringRef;
37 using llvm::sys::path::is_separator;
38 using llvm::sys::path::Style;
40 inline Style real_style(Style style) {
42 return (style == Style::posix) ? Style::posix : Style::windows;
44 return (style == Style::windows) ? Style::windows : Style::posix;
48 inline const char *separators(Style style) {
49 if (real_style(style) == Style::windows)
54 inline char preferred_separator(Style style) {
55 if (real_style(style) == Style::windows)
60 StringRef find_first_component(StringRef path, Style style) {
61 // Look for this first component in the following order.
62 // * empty (in this case we return an empty string)
63 // * either C: or {//,\\}net.
65 // * {file,directory}name
70 if (real_style(style) == Style::windows) {
72 if (path.size() >= 2 &&
73 std::isalpha(static_cast<unsigned char>(path[0])) && path[1] == ':')
74 return path.substr(0, 2);
78 if ((path.size() > 2) && is_separator(path[0], style) &&
79 path[0] == path[1] && !is_separator(path[2], style)) {
80 // Find the next directory separator.
81 size_t end = path.find_first_of(separators(style), 2);
82 return path.substr(0, end);
86 if (is_separator(path[0], style))
87 return path.substr(0, 1);
89 // * {file,directory}name
90 size_t end = path.find_first_of(separators(style));
91 return path.substr(0, end);
94 // Returns the first character of the filename in str. For paths ending in
95 // '/', it returns the position of the '/'.
96 size_t filename_pos(StringRef str, Style style) {
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 // Returns the position of the root directory in str. If there is no root
114 // directory in str, it returns StringRef::npos.
115 size_t root_dir_start(StringRef str, Style style) {
117 if (real_style(style) == Style::windows) {
118 if (str.size() > 2 && str[1] == ':' && is_separator(str[2], style))
123 if (str.size() > 3 && is_separator(str[0], style) && str[0] == str[1] &&
124 !is_separator(str[2], style)) {
125 return str.find_first_of(separators(style), 2);
129 if (str.size() > 0 && is_separator(str[0], style))
132 return StringRef::npos;
135 // Returns the position past the end of the "parent path" of path. The parent
136 // path will not end in '/', unless the parent is the root directory. If the
137 // path has no parent, 0 is returned.
138 size_t parent_path_end(StringRef path, Style style) {
139 size_t end_pos = filename_pos(path, style);
141 bool filename_was_sep =
142 path.size() > 0 && is_separator(path[end_pos], style);
144 // Skip separators until we reach root dir (or the start of the string).
145 size_t root_dir_pos = root_dir_start(path, style);
146 while (end_pos > 0 &&
147 (root_dir_pos == StringRef::npos || end_pos > root_dir_pos) &&
148 is_separator(path[end_pos - 1], style))
151 if (end_pos == root_dir_pos && !filename_was_sep) {
152 // We've reached the root dir and the input path was *not* ending in a
153 // sequence of slashes. Include the root dir in the parent path.
154 return root_dir_pos + 1;
157 // Otherwise, just include before the last slash.
160 } // end unnamed namespace
168 static std::error_code
169 createUniqueEntity(const Twine &Model, int &ResultFD,
170 SmallVectorImpl<char> &ResultPath, bool MakeAbsolute,
171 unsigned Mode, FSEntity Type,
172 sys::fs::OpenFlags Flags = sys::fs::OF_None) {
173 SmallString<128> ModelStorage;
174 Model.toVector(ModelStorage);
177 // Make model absolute by prepending a temp directory if it's not already.
178 if (!sys::path::is_absolute(Twine(ModelStorage))) {
179 SmallString<128> TDir;
180 sys::path::system_temp_directory(true, TDir);
181 sys::path::append(TDir, Twine(ModelStorage));
182 ModelStorage.swap(TDir);
186 // From here on, DO NOT modify model. It may be needed if the randomly chosen
187 // path already exists.
188 ResultPath = ModelStorage;
190 ResultPath.push_back(0);
191 ResultPath.pop_back();
194 // Replace '%' with random chars.
195 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
196 if (ModelStorage[i] == '%')
197 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
200 // Try to open + create the file.
203 if (std::error_code EC =
204 sys::fs::openFileForReadWrite(Twine(ResultPath.begin()), ResultFD,
205 sys::fs::CD_CreateNew, Flags, Mode)) {
206 if (EC == errc::file_exists)
207 goto retry_random_path;
211 return std::error_code();
216 sys::fs::access(ResultPath.begin(), sys::fs::AccessMode::Exist);
217 if (EC == errc::no_such_file_or_directory)
218 return std::error_code();
221 goto retry_random_path;
225 if (std::error_code EC =
226 sys::fs::create_directory(ResultPath.begin(), false)) {
227 if (EC == errc::file_exists)
228 goto retry_random_path;
231 return std::error_code();
234 llvm_unreachable("Invalid Type");
241 const_iterator begin(StringRef path, Style style) {
244 i.Component = find_first_component(path, style);
250 const_iterator end(StringRef path) {
253 i.Position = path.size();
257 const_iterator &const_iterator::operator++() {
258 assert(Position < Path.size() && "Tried to increment past end!");
260 // Increment Position to past the current component
261 Position += Component.size();
264 if (Position == Path.size()) {
265 Component = StringRef();
269 // Both POSIX and Windows treat paths that begin with exactly two separators
271 bool was_net = Component.size() > 2 && is_separator(Component[0], S) &&
272 Component[1] == Component[0] && !is_separator(Component[2], S);
274 // Handle separators.
275 if (is_separator(Path[Position], S)) {
279 (real_style(S) == Style::windows && Component.endswith(":"))) {
280 Component = Path.substr(Position, 1);
284 // Skip extra separators.
285 while (Position != Path.size() && is_separator(Path[Position], S)) {
289 // Treat trailing '/' as a '.', unless it is the root dir.
290 if (Position == Path.size() && Component != "/") {
297 // Find next component.
298 size_t end_pos = Path.find_first_of(separators(S), Position);
299 Component = Path.slice(Position, end_pos);
304 bool const_iterator::operator==(const const_iterator &RHS) const {
305 return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
308 ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
309 return Position - RHS.Position;
312 reverse_iterator rbegin(StringRef Path, Style style) {
315 I.Position = Path.size();
320 reverse_iterator rend(StringRef Path) {
323 I.Component = Path.substr(0, 0);
328 reverse_iterator &reverse_iterator::operator++() {
329 size_t root_dir_pos = root_dir_start(Path, S);
331 // Skip separators unless it's the root directory.
332 size_t end_pos = Position;
333 while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
334 is_separator(Path[end_pos - 1], S))
337 // Treat trailing '/' as a '.', unless it is the root dir.
338 if (Position == Path.size() && !Path.empty() &&
339 is_separator(Path.back(), S) &&
340 (root_dir_pos == StringRef::npos || end_pos - 1 > root_dir_pos)) {
346 // Find next separator.
347 size_t start_pos = filename_pos(Path.substr(0, end_pos), S);
348 Component = Path.slice(start_pos, end_pos);
349 Position = start_pos;
353 bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
354 return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
355 Position == RHS.Position;
358 ptrdiff_t reverse_iterator::operator-(const reverse_iterator &RHS) const {
359 return Position - RHS.Position;
362 StringRef root_path(StringRef path, Style style) {
363 const_iterator b = begin(path, style), pos = b, e = end(path);
366 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
367 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
369 if (has_net || has_drive) {
370 if ((++pos != e) && is_separator((*pos)[0], style)) {
371 // {C:/,//net/}, so get the first two components.
372 return path.substr(0, b->size() + pos->size());
374 // just {C:,//net}, return the first component.
379 // POSIX style root directory.
380 if (is_separator((*b)[0], style)) {
388 StringRef root_name(StringRef path, Style style) {
389 const_iterator b = begin(path, style), e = end(path);
392 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
393 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
395 if (has_net || has_drive) {
396 // just {C:,//net}, return the first component.
401 // No path or no name.
405 StringRef root_directory(StringRef path, Style style) {
406 const_iterator b = begin(path, style), pos = b, e = end(path);
409 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
410 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
412 if ((has_net || has_drive) &&
413 // {C:,//net}, skip to the next component.
414 (++pos != e) && is_separator((*pos)[0], style)) {
418 // POSIX style root directory.
419 if (!has_net && is_separator((*b)[0], style)) {
424 // No path or no root.
428 StringRef relative_path(StringRef path, Style style) {
429 StringRef root = root_path(path, style);
430 return path.substr(root.size());
433 void append(SmallVectorImpl<char> &path, Style style, const Twine &a,
434 const Twine &b, const Twine &c, const Twine &d) {
435 SmallString<32> a_storage;
436 SmallString<32> b_storage;
437 SmallString<32> c_storage;
438 SmallString<32> d_storage;
440 SmallVector<StringRef, 4> components;
441 if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
442 if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
443 if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
444 if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
446 for (auto &component : components) {
448 !path.empty() && is_separator(path[path.size() - 1], style);
450 // Strip separators from beginning of component.
451 size_t loc = component.find_first_not_of(separators(style));
452 StringRef c = component.substr(loc);
455 path.append(c.begin(), c.end());
459 bool component_has_sep =
460 !component.empty() && is_separator(component[0], style);
461 if (!component_has_sep &&
462 !(path.empty() || has_root_name(component, style))) {
464 path.push_back(preferred_separator(style));
467 path.append(component.begin(), component.end());
471 void append(SmallVectorImpl<char> &path, const Twine &a, const Twine &b,
472 const Twine &c, const Twine &d) {
473 append(path, Style::native, a, b, c, d);
476 void append(SmallVectorImpl<char> &path, const_iterator begin,
477 const_iterator end, Style style) {
478 for (; begin != end; ++begin)
479 path::append(path, style, *begin);
482 StringRef parent_path(StringRef path, Style style) {
483 size_t end_pos = parent_path_end(path, style);
484 if (end_pos == StringRef::npos)
487 return path.substr(0, end_pos);
490 void remove_filename(SmallVectorImpl<char> &path, Style style) {
491 size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()), style);
492 if (end_pos != StringRef::npos)
493 path.set_size(end_pos);
496 void replace_extension(SmallVectorImpl<char> &path, const Twine &extension,
498 StringRef p(path.begin(), path.size());
499 SmallString<32> ext_storage;
500 StringRef ext = extension.toStringRef(ext_storage);
502 // Erase existing extension.
503 size_t pos = p.find_last_of('.');
504 if (pos != StringRef::npos && pos >= filename_pos(p, style))
507 // Append '.' if needed.
508 if (ext.size() > 0 && ext[0] != '.')
512 path.append(ext.begin(), ext.end());
515 void replace_path_prefix(SmallVectorImpl<char> &Path,
516 const StringRef &OldPrefix, const StringRef &NewPrefix,
518 if (OldPrefix.empty() && NewPrefix.empty())
521 StringRef OrigPath(Path.begin(), Path.size());
522 if (!OrigPath.startswith(OldPrefix))
525 // If prefixes have the same size we can simply copy the new one over.
526 if (OldPrefix.size() == NewPrefix.size()) {
527 std::copy(NewPrefix.begin(), NewPrefix.end(), Path.begin());
531 StringRef RelPath = OrigPath.substr(OldPrefix.size());
532 SmallString<256> NewPath;
533 path::append(NewPath, style, NewPrefix);
534 path::append(NewPath, style, RelPath);
538 void native(const Twine &path, SmallVectorImpl<char> &result, Style style) {
539 assert((!path.isSingleStringRef() ||
540 path.getSingleStringRef().data() != result.data()) &&
541 "path and result are not allowed to overlap!");
544 path.toVector(result);
545 native(result, style);
548 void native(SmallVectorImpl<char> &Path, Style style) {
551 if (real_style(style) == Style::windows) {
552 std::replace(Path.begin(), Path.end(), '/', '\\');
553 if (Path[0] == '~' && (Path.size() == 1 || is_separator(Path[1], style))) {
554 SmallString<128> PathHome;
555 home_directory(PathHome);
556 PathHome.append(Path.begin() + 1, Path.end());
560 for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
563 if (PN < PE && *PN == '\\')
564 ++PI; // increment once, the for loop will move over the escaped slash
572 std::string convert_to_slash(StringRef path, Style style) {
573 if (real_style(style) != Style::windows)
576 std::string s = path.str();
577 std::replace(s.begin(), s.end(), '\\', '/');
581 StringRef filename(StringRef path, Style style) { return *rbegin(path, style); }
583 StringRef stem(StringRef path, Style style) {
584 StringRef fname = filename(path, style);
585 size_t pos = fname.find_last_of('.');
586 if (pos == StringRef::npos)
589 if ((fname.size() == 1 && fname == ".") ||
590 (fname.size() == 2 && fname == ".."))
593 return fname.substr(0, pos);
596 StringRef extension(StringRef path, Style style) {
597 StringRef fname = filename(path, style);
598 size_t pos = fname.find_last_of('.');
599 if (pos == StringRef::npos)
602 if ((fname.size() == 1 && fname == ".") ||
603 (fname.size() == 2 && fname == ".."))
606 return fname.substr(pos);
609 bool is_separator(char value, Style style) {
612 if (real_style(style) == Style::windows)
613 return value == '\\';
617 StringRef get_separator(Style style) {
618 if (real_style(style) == Style::windows)
623 bool has_root_name(const Twine &path, Style style) {
624 SmallString<128> path_storage;
625 StringRef p = path.toStringRef(path_storage);
627 return !root_name(p, style).empty();
630 bool has_root_directory(const Twine &path, Style style) {
631 SmallString<128> path_storage;
632 StringRef p = path.toStringRef(path_storage);
634 return !root_directory(p, style).empty();
637 bool has_root_path(const Twine &path, Style style) {
638 SmallString<128> path_storage;
639 StringRef p = path.toStringRef(path_storage);
641 return !root_path(p, style).empty();
644 bool has_relative_path(const Twine &path, Style style) {
645 SmallString<128> path_storage;
646 StringRef p = path.toStringRef(path_storage);
648 return !relative_path(p, style).empty();
651 bool has_filename(const Twine &path, Style style) {
652 SmallString<128> path_storage;
653 StringRef p = path.toStringRef(path_storage);
655 return !filename(p, style).empty();
658 bool has_parent_path(const Twine &path, Style style) {
659 SmallString<128> path_storage;
660 StringRef p = path.toStringRef(path_storage);
662 return !parent_path(p, style).empty();
665 bool has_stem(const Twine &path, Style style) {
666 SmallString<128> path_storage;
667 StringRef p = path.toStringRef(path_storage);
669 return !stem(p, style).empty();
672 bool has_extension(const Twine &path, Style style) {
673 SmallString<128> path_storage;
674 StringRef p = path.toStringRef(path_storage);
676 return !extension(p, style).empty();
679 bool is_absolute(const Twine &path, Style style) {
680 SmallString<128> path_storage;
681 StringRef p = path.toStringRef(path_storage);
683 bool rootDir = has_root_directory(p, style);
685 (real_style(style) != Style::windows) || has_root_name(p, style);
687 return rootDir && rootName;
690 bool is_relative(const Twine &path, Style style) {
691 return !is_absolute(path, style);
694 StringRef remove_leading_dotslash(StringRef Path, Style style) {
695 // Remove leading "./" (or ".//" or "././" etc.)
696 while (Path.size() > 2 && Path[0] == '.' && is_separator(Path[1], style)) {
697 Path = Path.substr(2);
698 while (Path.size() > 0 && is_separator(Path[0], style))
699 Path = Path.substr(1);
704 static SmallString<256> remove_dots(StringRef path, bool remove_dot_dot,
706 SmallVector<StringRef, 16> components;
708 // Skip the root path, then look for traversal in the components.
709 StringRef rel = path::relative_path(path, style);
711 llvm::make_range(path::begin(rel, style), path::end(rel))) {
714 // Leading ".." will remain in the path unless it's at the root.
715 if (remove_dot_dot && C == "..") {
716 if (!components.empty() && components.back() != "..") {
717 components.pop_back();
720 if (path::is_absolute(path, style))
723 components.push_back(C);
726 SmallString<256> buffer = path::root_path(path, style);
727 for (StringRef C : components)
728 path::append(buffer, style, C);
732 bool remove_dots(SmallVectorImpl<char> &path, bool remove_dot_dot,
734 StringRef p(path.data(), path.size());
736 SmallString<256> result = remove_dots(p, remove_dot_dot, style);
744 } // end namespace path
748 std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
750 std::error_code EC = status(Path, Status);
753 Result = Status.getUniqueID();
754 return std::error_code();
757 std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
758 SmallVectorImpl<char> &ResultPath,
760 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
763 static std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
764 SmallVectorImpl<char> &ResultPath,
765 unsigned Mode, OpenFlags Flags) {
766 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File,
770 std::error_code createUniqueFile(const Twine &Model,
771 SmallVectorImpl<char> &ResultPath,
774 auto EC = createUniqueFile(Model, FD, ResultPath, Mode);
777 // FD is only needed to avoid race conditions. Close it right away.
782 static std::error_code
783 createTemporaryFile(const Twine &Model, int &ResultFD,
784 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
785 SmallString<128> Storage;
786 StringRef P = Model.toNullTerminatedStringRef(Storage);
787 assert(P.find_first_of(separators(Style::native)) == StringRef::npos &&
788 "Model must be a simple filename.");
789 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
790 return createUniqueEntity(P.begin(), ResultFD, ResultPath, true,
791 owner_read | owner_write, Type);
794 static std::error_code
795 createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
796 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
797 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
798 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
802 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
804 SmallVectorImpl<char> &ResultPath) {
805 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
808 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
809 SmallVectorImpl<char> &ResultPath) {
811 auto EC = createTemporaryFile(Prefix, Suffix, FD, ResultPath);
814 // FD is only needed to avoid race conditions. Close it right away.
820 // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
821 // for consistency. We should try using mkdtemp.
822 std::error_code createUniqueDirectory(const Twine &Prefix,
823 SmallVectorImpl<char> &ResultPath) {
825 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath, true, 0,
830 getPotentiallyUniqueFileName(const Twine &Model,
831 SmallVectorImpl<char> &ResultPath) {
833 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
837 getPotentiallyUniqueTempFileName(const Twine &Prefix, StringRef Suffix,
838 SmallVectorImpl<char> &ResultPath) {
840 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
843 static std::error_code make_absolute(const Twine ¤t_directory,
844 SmallVectorImpl<char> &path,
845 bool use_current_directory) {
846 StringRef p(path.data(), path.size());
848 bool rootDirectory = path::has_root_directory(p);
850 (real_style(Style::native) != Style::windows) || path::has_root_name(p);
853 if (rootName && rootDirectory)
854 return std::error_code();
856 // All of the following conditions will need the current directory.
857 SmallString<128> current_dir;
858 if (use_current_directory)
859 current_directory.toVector(current_dir);
860 else if (std::error_code ec = current_path(current_dir))
863 // Relative path. Prepend the current directory.
864 if (!rootName && !rootDirectory) {
865 // Append path to the current directory.
866 path::append(current_dir, p);
867 // Set path to the result.
868 path.swap(current_dir);
869 return std::error_code();
872 if (!rootName && rootDirectory) {
873 StringRef cdrn = path::root_name(current_dir);
874 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
875 path::append(curDirRootName, p);
876 // Set path to the result.
877 path.swap(curDirRootName);
878 return std::error_code();
881 if (rootName && !rootDirectory) {
882 StringRef pRootName = path::root_name(p);
883 StringRef bRootDirectory = path::root_directory(current_dir);
884 StringRef bRelativePath = path::relative_path(current_dir);
885 StringRef pRelativePath = path::relative_path(p);
887 SmallString<128> res;
888 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
890 return std::error_code();
893 llvm_unreachable("All rootName and rootDirectory combinations should have "
897 std::error_code make_absolute(const Twine ¤t_directory,
898 SmallVectorImpl<char> &path) {
899 return make_absolute(current_directory, path, true);
902 std::error_code make_absolute(SmallVectorImpl<char> &path) {
903 return make_absolute(Twine(), path, false);
906 std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
908 SmallString<128> PathStorage;
909 StringRef P = Path.toStringRef(PathStorage);
911 // Be optimistic and try to create the directory
912 std::error_code EC = create_directory(P, IgnoreExisting, Perms);
913 // If we succeeded, or had any error other than the parent not existing, just
915 if (EC != errc::no_such_file_or_directory)
918 // We failed because of a no_such_file_or_directory, try to create the
920 StringRef Parent = path::parent_path(P);
924 if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
927 return create_directory(P, IgnoreExisting, Perms);
930 static std::error_code copy_file_internal(int ReadFD, int WriteFD) {
931 const size_t BufSize = 4096;
932 char *Buf = new char[BufSize];
933 int BytesRead = 0, BytesWritten = 0;
935 BytesRead = read(ReadFD, Buf, BufSize);
939 BytesWritten = write(WriteFD, Buf, BytesRead);
940 if (BytesWritten < 0)
942 BytesRead -= BytesWritten;
944 if (BytesWritten < 0)
949 if (BytesRead < 0 || BytesWritten < 0)
950 return std::error_code(errno, std::generic_category());
951 return std::error_code();
954 std::error_code copy_file(const Twine &From, const Twine &To) {
956 if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
958 if (std::error_code EC =
959 openFileForWrite(To, WriteFD, CD_CreateAlways, OF_None)) {
964 std::error_code EC = copy_file_internal(ReadFD, WriteFD);
972 std::error_code copy_file(const Twine &From, int ToFD) {
974 if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
977 std::error_code EC = copy_file_internal(ReadFD, ToFD);
984 ErrorOr<MD5::MD5Result> md5_contents(int FD) {
987 constexpr size_t BufSize = 4096;
988 std::vector<uint8_t> Buf(BufSize);
991 BytesRead = read(FD, Buf.data(), BufSize);
994 Hash.update(makeArrayRef(Buf.data(), BytesRead));
998 return std::error_code(errno, std::generic_category());
999 MD5::MD5Result Result;
1004 ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path) {
1006 if (auto EC = openFileForRead(Path, FD, OF_None))
1009 auto Result = md5_contents(FD);
1014 bool exists(const basic_file_status &status) {
1015 return status_known(status) && status.type() != file_type::file_not_found;
1018 bool status_known(const basic_file_status &s) {
1019 return s.type() != file_type::status_error;
1022 file_type get_file_type(const Twine &Path, bool Follow) {
1024 if (status(Path, st, Follow))
1025 return file_type::status_error;
1029 bool is_directory(const basic_file_status &status) {
1030 return status.type() == file_type::directory_file;
1033 std::error_code is_directory(const Twine &path, bool &result) {
1035 if (std::error_code ec = status(path, st))
1037 result = is_directory(st);
1038 return std::error_code();
1041 bool is_regular_file(const basic_file_status &status) {
1042 return status.type() == file_type::regular_file;
1045 std::error_code is_regular_file(const Twine &path, bool &result) {
1047 if (std::error_code ec = status(path, st))
1049 result = is_regular_file(st);
1050 return std::error_code();
1053 bool is_symlink_file(const basic_file_status &status) {
1054 return status.type() == file_type::symlink_file;
1057 std::error_code is_symlink_file(const Twine &path, bool &result) {
1059 if (std::error_code ec = status(path, st, false))
1061 result = is_symlink_file(st);
1062 return std::error_code();
1065 bool is_other(const basic_file_status &status) {
1066 return exists(status) &&
1067 !is_regular_file(status) &&
1068 !is_directory(status);
1071 std::error_code is_other(const Twine &Path, bool &Result) {
1072 file_status FileStatus;
1073 if (std::error_code EC = status(Path, FileStatus))
1075 Result = is_other(FileStatus);
1076 return std::error_code();
1079 void directory_entry::replace_filename(const Twine &filename,
1080 basic_file_status st) {
1081 SmallString<128> path = path::parent_path(Path);
1082 path::append(path, filename);
1087 ErrorOr<perms> getPermissions(const Twine &Path) {
1089 if (std::error_code EC = status(Path, Status))
1092 return Status.permissions();
1095 } // end namespace fs
1096 } // end namespace sys
1097 } // end namespace llvm
1099 // Include the truly platform-specific parts.
1100 #if defined(LLVM_ON_UNIX)
1101 #include "Unix/Path.inc"
1104 #include "Windows/Path.inc"
1110 TempFile::TempFile(StringRef Name, int FD) : TmpName(Name), FD(FD) {}
1111 TempFile::TempFile(TempFile &&Other) { *this = std::move(Other); }
1112 TempFile &TempFile::operator=(TempFile &&Other) {
1113 TmpName = std::move(Other.TmpName);
1119 TempFile::~TempFile() { assert(Done); }
1121 Error TempFile::discard() {
1123 std::error_code RemoveEC;
1124 // On windows closing will remove the file.
1126 // Always try to close and remove.
1127 if (!TmpName.empty()) {
1128 RemoveEC = fs::remove(TmpName);
1129 sys::DontRemoveFileOnSignal(TmpName);
1136 if (FD != -1 && close(FD) == -1) {
1137 std::error_code EC = std::error_code(errno, std::generic_category());
1138 return errorCodeToError(EC);
1142 return errorCodeToError(RemoveEC);
1145 Error TempFile::keep(const Twine &Name) {
1148 // Always try to close and rename.
1150 // If we can't cancel the delete don't rename.
1151 auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1152 std::error_code RenameEC = setDeleteDisposition(H, false);
1154 RenameEC = rename_fd(FD, Name);
1155 // If we can't rename, discard the temporary file.
1157 setDeleteDisposition(H, true);
1159 std::error_code RenameEC = fs::rename(TmpName, Name);
1161 // If we can't rename, try to copy to work around cross-device link issues.
1162 RenameEC = sys::fs::copy_file(TmpName, Name);
1163 // If we can't rename or copy, discard the temporary file.
1167 sys::DontRemoveFileOnSignal(TmpName);
1173 if (close(FD) == -1) {
1174 std::error_code EC(errno, std::generic_category());
1175 return errorCodeToError(EC);
1179 return errorCodeToError(RenameEC);
1182 Error TempFile::keep() {
1187 auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1188 if (std::error_code EC = setDeleteDisposition(H, false))
1189 return errorCodeToError(EC);
1191 sys::DontRemoveFileOnSignal(TmpName);
1196 if (close(FD) == -1) {
1197 std::error_code EC(errno, std::generic_category());
1198 return errorCodeToError(EC);
1202 return Error::success();
1205 Expected<TempFile> TempFile::create(const Twine &Model, unsigned Mode) {
1207 SmallString<128> ResultPath;
1208 if (std::error_code EC =
1209 createUniqueFile(Model, FD, ResultPath, Mode, OF_Delete))
1210 return errorCodeToError(EC);
1212 TempFile Ret(ResultPath, FD);
1214 if (sys::RemoveFileOnSignal(ResultPath)) {
1215 // Make sure we delete the file when RemoveFileOnSignal fails.
1216 consumeError(Ret.discard());
1217 std::error_code EC(errc::operation_not_permitted);
1218 return errorCodeToError(EC);
1221 return std::move(Ret);
1227 bool user_cache_directory(SmallVectorImpl<char> &Result, const Twine &Path1,
1228 const Twine &Path2, const Twine &Path3) {
1229 if (getUserCacheDir(Result)) {
1230 append(Result, Path1, Path2, Path3);
1236 } // end namespace path
1237 } // end namsspace sys
1238 } // end namespace llvm