1 //===-- Path.cpp - Implement OS Path Concept ------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the operating system Path API.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Support/Path.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/ScopeExit.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Config/config.h"
18 #include "llvm/Config/llvm-config.h"
19 #include "llvm/Support/Endian.h"
20 #include "llvm/Support/Errc.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/Process.h"
24 #include "llvm/Support/Signals.h"
27 #if !defined(_MSC_VER) && !defined(__MINGW32__)
34 using namespace llvm::support::endian
;
37 using llvm::StringRef
;
38 using llvm::sys::path::is_separator
;
39 using llvm::sys::path::Style
;
41 inline Style
real_style(Style style
) {
42 if (style
!= Style::native
)
44 if (is_style_posix(style
))
46 return LLVM_WINDOWS_PREFER_FORWARD_SLASH
? Style::windows_slash
47 : Style::windows_backslash
;
50 inline const char *separators(Style style
) {
51 if (is_style_windows(style
))
56 inline char preferred_separator(Style style
) {
57 if (real_style(style
) == Style::windows
)
62 StringRef
find_first_component(StringRef path
, Style style
) {
63 // Look for this first component in the following order.
64 // * empty (in this case we return an empty string)
65 // * either C: or {//,\\}net.
67 // * {file,directory}name
72 if (is_style_windows(style
)) {
74 if (path
.size() >= 2 &&
75 std::isalpha(static_cast<unsigned char>(path
[0])) && path
[1] == ':')
76 return path
.substr(0, 2);
80 if ((path
.size() > 2) && is_separator(path
[0], style
) &&
81 path
[0] == path
[1] && !is_separator(path
[2], style
)) {
82 // Find the next directory separator.
83 size_t end
= path
.find_first_of(separators(style
), 2);
84 return path
.substr(0, end
);
88 if (is_separator(path
[0], style
))
89 return path
.substr(0, 1);
91 // * {file,directory}name
92 size_t end
= path
.find_first_of(separators(style
));
93 return path
.substr(0, end
);
96 // Returns the first character of the filename in str. For paths ending in
97 // '/', it returns the position of the '/'.
98 size_t filename_pos(StringRef str
, Style style
) {
99 if (str
.size() > 0 && is_separator(str
[str
.size() - 1], style
))
100 return str
.size() - 1;
102 size_t pos
= str
.find_last_of(separators(style
), str
.size() - 1);
104 if (is_style_windows(style
)) {
105 if (pos
== StringRef::npos
)
106 pos
= str
.find_last_of(':', str
.size() - 1);
109 if (pos
== StringRef::npos
|| (pos
== 1 && is_separator(str
[0], style
)))
115 // Returns the position of the root directory in str. If there is no root
116 // directory in str, it returns StringRef::npos.
117 size_t root_dir_start(StringRef str
, Style style
) {
119 if (is_style_windows(style
)) {
120 if (str
.size() > 2 && str
[1] == ':' && is_separator(str
[2], style
))
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 // Returns the position past the end of the "parent path" of path. The parent
138 // path will not end in '/', unless the parent is the root directory. If the
139 // path has no parent, 0 is returned.
140 size_t parent_path_end(StringRef path
, Style style
) {
141 size_t end_pos
= filename_pos(path
, style
);
143 bool filename_was_sep
=
144 path
.size() > 0 && is_separator(path
[end_pos
], style
);
146 // Skip separators until we reach root dir (or the start of the string).
147 size_t root_dir_pos
= root_dir_start(path
, style
);
148 while (end_pos
> 0 &&
149 (root_dir_pos
== StringRef::npos
|| end_pos
> root_dir_pos
) &&
150 is_separator(path
[end_pos
- 1], style
))
153 if (end_pos
== root_dir_pos
&& !filename_was_sep
) {
154 // We've reached the root dir and the input path was *not* ending in a
155 // sequence of slashes. Include the root dir in the parent path.
156 return root_dir_pos
+ 1;
159 // Otherwise, just include before the last slash.
162 } // end unnamed namespace
170 static std::error_code
171 createUniqueEntity(const Twine
&Model
, int &ResultFD
,
172 SmallVectorImpl
<char> &ResultPath
, bool MakeAbsolute
,
173 FSEntity Type
, sys::fs::OpenFlags Flags
= sys::fs::OF_None
,
176 // Limit the number of attempts we make, so that we don't infinite loop. E.g.
177 // "permission denied" could be for a specific file (so we retry with a
178 // different name) or for the whole directory (retry would always fail).
179 // Checking which is racy, so we try a number of times, then give up.
181 for (int Retries
= 128; Retries
> 0; --Retries
) {
182 sys::fs::createUniquePath(Model
, ResultPath
, MakeAbsolute
);
183 // Try to open + create the file.
186 EC
= sys::fs::openFileForReadWrite(Twine(ResultPath
.begin()), ResultFD
,
187 sys::fs::CD_CreateNew
, Flags
, Mode
);
189 // errc::permission_denied happens on Windows when we try to open a file
190 // that has been marked for deletion.
191 if (EC
== errc::file_exists
|| EC
== errc::permission_denied
)
196 return std::error_code();
200 EC
= sys::fs::access(ResultPath
.begin(), sys::fs::AccessMode::Exist
);
201 if (EC
== errc::no_such_file_or_directory
)
202 return std::error_code();
209 EC
= sys::fs::create_directory(ResultPath
.begin(), false);
211 if (EC
== errc::file_exists
)
215 return std::error_code();
218 llvm_unreachable("Invalid Type");
227 const_iterator
begin(StringRef path
, Style style
) {
230 i
.Component
= find_first_component(path
, style
);
236 const_iterator
end(StringRef path
) {
239 i
.Position
= path
.size();
243 const_iterator
&const_iterator::operator++() {
244 assert(Position
< Path
.size() && "Tried to increment past end!");
246 // Increment Position to past the current component
247 Position
+= Component
.size();
250 if (Position
== Path
.size()) {
251 Component
= StringRef();
255 // Both POSIX and Windows treat paths that begin with exactly two separators
257 bool was_net
= Component
.size() > 2 && is_separator(Component
[0], S
) &&
258 Component
[1] == Component
[0] && !is_separator(Component
[2], S
);
260 // Handle separators.
261 if (is_separator(Path
[Position
], S
)) {
265 (is_style_windows(S
) && Component
.ends_with(":"))) {
266 Component
= Path
.substr(Position
, 1);
270 // Skip extra separators.
271 while (Position
!= Path
.size() && is_separator(Path
[Position
], S
)) {
275 // Treat trailing '/' as a '.', unless it is the root dir.
276 if (Position
== Path
.size() && Component
!= "/") {
283 // Find next component.
284 size_t end_pos
= Path
.find_first_of(separators(S
), Position
);
285 Component
= Path
.slice(Position
, end_pos
);
290 bool const_iterator::operator==(const const_iterator
&RHS
) const {
291 return Path
.begin() == RHS
.Path
.begin() && Position
== RHS
.Position
;
294 ptrdiff_t const_iterator::operator-(const const_iterator
&RHS
) const {
295 return Position
- RHS
.Position
;
298 reverse_iterator
rbegin(StringRef Path
, Style style
) {
301 I
.Position
= Path
.size();
307 reverse_iterator
rend(StringRef Path
) {
310 I
.Component
= Path
.substr(0, 0);
315 reverse_iterator
&reverse_iterator::operator++() {
316 size_t root_dir_pos
= root_dir_start(Path
, S
);
318 // Skip separators unless it's the root directory.
319 size_t end_pos
= Position
;
320 while (end_pos
> 0 && (end_pos
- 1) != root_dir_pos
&&
321 is_separator(Path
[end_pos
- 1], S
))
324 // Treat trailing '/' as a '.', unless it is the root dir.
325 if (Position
== Path
.size() && !Path
.empty() &&
326 is_separator(Path
.back(), S
) &&
327 (root_dir_pos
== StringRef::npos
|| end_pos
- 1 > root_dir_pos
)) {
333 // Find next separator.
334 size_t start_pos
= filename_pos(Path
.substr(0, end_pos
), S
);
335 Component
= Path
.slice(start_pos
, end_pos
);
336 Position
= start_pos
;
340 bool reverse_iterator::operator==(const reverse_iterator
&RHS
) const {
341 return Path
.begin() == RHS
.Path
.begin() && Component
== RHS
.Component
&&
342 Position
== RHS
.Position
;
345 ptrdiff_t reverse_iterator::operator-(const reverse_iterator
&RHS
) const {
346 return Position
- RHS
.Position
;
349 StringRef
root_path(StringRef path
, Style style
) {
350 const_iterator b
= begin(path
, style
), pos
= b
, e
= end(path
);
353 b
->size() > 2 && is_separator((*b
)[0], style
) && (*b
)[1] == (*b
)[0];
354 bool has_drive
= is_style_windows(style
) && b
->ends_with(":");
356 if (has_net
|| has_drive
) {
357 if ((++pos
!= e
) && is_separator((*pos
)[0], style
)) {
358 // {C:/,//net/}, so get the first two components.
359 return path
.substr(0, b
->size() + pos
->size());
361 // just {C:,//net}, return the first component.
365 // POSIX style root directory.
366 if (is_separator((*b
)[0], style
)) {
374 StringRef
root_name(StringRef path
, Style style
) {
375 const_iterator b
= begin(path
, style
), e
= end(path
);
378 b
->size() > 2 && is_separator((*b
)[0], style
) && (*b
)[1] == (*b
)[0];
379 bool has_drive
= is_style_windows(style
) && b
->ends_with(":");
381 if (has_net
|| has_drive
) {
382 // just {C:,//net}, return the first component.
387 // No path or no name.
391 StringRef
root_directory(StringRef path
, Style style
) {
392 const_iterator b
= begin(path
, style
), pos
= b
, e
= end(path
);
395 b
->size() > 2 && is_separator((*b
)[0], style
) && (*b
)[1] == (*b
)[0];
396 bool has_drive
= is_style_windows(style
) && b
->ends_with(":");
398 if ((has_net
|| has_drive
) &&
399 // {C:,//net}, skip to the next component.
400 (++pos
!= e
) && is_separator((*pos
)[0], style
)) {
404 // POSIX style root directory.
405 if (!has_net
&& is_separator((*b
)[0], style
)) {
410 // No path or no root.
414 StringRef
relative_path(StringRef path
, Style style
) {
415 StringRef root
= root_path(path
, style
);
416 return path
.substr(root
.size());
419 void append(SmallVectorImpl
<char> &path
, Style style
, const Twine
&a
,
420 const Twine
&b
, const Twine
&c
, const Twine
&d
) {
421 SmallString
<32> a_storage
;
422 SmallString
<32> b_storage
;
423 SmallString
<32> c_storage
;
424 SmallString
<32> d_storage
;
426 SmallVector
<StringRef
, 4> components
;
427 if (!a
.isTriviallyEmpty()) components
.push_back(a
.toStringRef(a_storage
));
428 if (!b
.isTriviallyEmpty()) components
.push_back(b
.toStringRef(b_storage
));
429 if (!c
.isTriviallyEmpty()) components
.push_back(c
.toStringRef(c_storage
));
430 if (!d
.isTriviallyEmpty()) components
.push_back(d
.toStringRef(d_storage
));
432 for (auto &component
: components
) {
434 !path
.empty() && is_separator(path
[path
.size() - 1], style
);
436 // Strip separators from beginning of component.
437 size_t loc
= component
.find_first_not_of(separators(style
));
438 StringRef c
= component
.substr(loc
);
441 path
.append(c
.begin(), c
.end());
445 bool component_has_sep
=
446 !component
.empty() && is_separator(component
[0], style
);
447 if (!component_has_sep
&&
448 !(path
.empty() || has_root_name(component
, style
))) {
450 path
.push_back(preferred_separator(style
));
453 path
.append(component
.begin(), component
.end());
457 void append(SmallVectorImpl
<char> &path
, const Twine
&a
, const Twine
&b
,
458 const Twine
&c
, const Twine
&d
) {
459 append(path
, Style::native
, a
, b
, c
, d
);
462 void append(SmallVectorImpl
<char> &path
, const_iterator begin
,
463 const_iterator end
, Style style
) {
464 for (; begin
!= end
; ++begin
)
465 path::append(path
, style
, *begin
);
468 StringRef
parent_path(StringRef path
, Style style
) {
469 size_t end_pos
= parent_path_end(path
, style
);
470 if (end_pos
== StringRef::npos
)
472 return path
.substr(0, end_pos
);
475 void remove_filename(SmallVectorImpl
<char> &path
, Style style
) {
476 size_t end_pos
= parent_path_end(StringRef(path
.begin(), path
.size()), style
);
477 if (end_pos
!= StringRef::npos
)
478 path
.truncate(end_pos
);
481 void replace_extension(SmallVectorImpl
<char> &path
, const Twine
&extension
,
483 StringRef
p(path
.begin(), path
.size());
484 SmallString
<32> ext_storage
;
485 StringRef ext
= extension
.toStringRef(ext_storage
);
487 // Erase existing extension.
488 size_t pos
= p
.find_last_of('.');
489 if (pos
!= StringRef::npos
&& pos
>= filename_pos(p
, style
))
492 // Append '.' if needed.
493 if (ext
.size() > 0 && ext
[0] != '.')
497 path
.append(ext
.begin(), ext
.end());
500 static bool starts_with(StringRef Path
, StringRef Prefix
,
501 Style style
= Style::native
) {
502 // Windows prefix matching : case and separator insensitive
503 if (is_style_windows(style
)) {
504 if (Path
.size() < Prefix
.size())
506 for (size_t I
= 0, E
= Prefix
.size(); I
!= E
; ++I
) {
507 bool SepPath
= is_separator(Path
[I
], style
);
508 bool SepPrefix
= is_separator(Prefix
[I
], style
);
509 if (SepPath
!= SepPrefix
)
511 if (!SepPath
&& toLower(Path
[I
]) != toLower(Prefix
[I
]))
516 return Path
.starts_with(Prefix
);
519 bool replace_path_prefix(SmallVectorImpl
<char> &Path
, StringRef OldPrefix
,
520 StringRef NewPrefix
, Style style
) {
521 if (OldPrefix
.empty() && NewPrefix
.empty())
524 StringRef
OrigPath(Path
.begin(), Path
.size());
525 if (!starts_with(OrigPath
, OldPrefix
, style
))
528 // If prefixes have the same size we can simply copy the new one over.
529 if (OldPrefix
.size() == NewPrefix
.size()) {
530 llvm::copy(NewPrefix
, Path
.begin());
534 StringRef RelPath
= OrigPath
.substr(OldPrefix
.size());
535 SmallString
<256> NewPath
;
536 (Twine(NewPrefix
) + RelPath
).toVector(NewPath
);
541 void native(const Twine
&path
, SmallVectorImpl
<char> &result
, Style style
) {
542 assert((!path
.isSingleStringRef() ||
543 path
.getSingleStringRef().data() != result
.data()) &&
544 "path and result are not allowed to overlap!");
547 path
.toVector(result
);
548 native(result
, style
);
551 void native(SmallVectorImpl
<char> &Path
, Style style
) {
554 if (is_style_windows(style
)) {
555 for (char &Ch
: Path
)
556 if (is_separator(Ch
, style
))
557 Ch
= preferred_separator(style
);
558 if (Path
[0] == '~' && (Path
.size() == 1 || is_separator(Path
[1], style
))) {
559 SmallString
<128> PathHome
;
560 home_directory(PathHome
);
561 PathHome
.append(Path
.begin() + 1, Path
.end());
565 std::replace(Path
.begin(), Path
.end(), '\\', '/');
569 std::string
convert_to_slash(StringRef path
, Style style
) {
570 if (is_style_posix(style
))
571 return std::string(path
);
573 std::string s
= path
.str();
574 std::replace(s
.begin(), s
.end(), '\\', '/');
578 StringRef
filename(StringRef path
, Style style
) { return *rbegin(path
, style
); }
580 StringRef
stem(StringRef path
, Style style
) {
581 StringRef fname
= filename(path
, style
);
582 size_t pos
= fname
.find_last_of('.');
583 if (pos
== StringRef::npos
)
585 if ((fname
.size() == 1 && fname
== ".") ||
586 (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
)
596 if ((fname
.size() == 1 && fname
== ".") ||
597 (fname
.size() == 2 && fname
== ".."))
599 return fname
.substr(pos
);
602 bool is_separator(char value
, Style style
) {
605 if (is_style_windows(style
))
606 return value
== '\\';
610 StringRef
get_separator(Style style
) {
611 if (real_style(style
) == Style::windows
)
616 bool has_root_name(const Twine
&path
, Style style
) {
617 SmallString
<128> path_storage
;
618 StringRef p
= path
.toStringRef(path_storage
);
620 return !root_name(p
, style
).empty();
623 bool has_root_directory(const Twine
&path
, Style style
) {
624 SmallString
<128> path_storage
;
625 StringRef p
= path
.toStringRef(path_storage
);
627 return !root_directory(p
, style
).empty();
630 bool has_root_path(const Twine
&path
, Style style
) {
631 SmallString
<128> path_storage
;
632 StringRef p
= path
.toStringRef(path_storage
);
634 return !root_path(p
, style
).empty();
637 bool has_relative_path(const Twine
&path
, Style style
) {
638 SmallString
<128> path_storage
;
639 StringRef p
= path
.toStringRef(path_storage
);
641 return !relative_path(p
, style
).empty();
644 bool has_filename(const Twine
&path
, Style style
) {
645 SmallString
<128> path_storage
;
646 StringRef p
= path
.toStringRef(path_storage
);
648 return !filename(p
, style
).empty();
651 bool has_parent_path(const Twine
&path
, Style style
) {
652 SmallString
<128> path_storage
;
653 StringRef p
= path
.toStringRef(path_storage
);
655 return !parent_path(p
, style
).empty();
658 bool has_stem(const Twine
&path
, Style style
) {
659 SmallString
<128> path_storage
;
660 StringRef p
= path
.toStringRef(path_storage
);
662 return !stem(p
, style
).empty();
665 bool has_extension(const Twine
&path
, Style style
) {
666 SmallString
<128> path_storage
;
667 StringRef p
= path
.toStringRef(path_storage
);
669 return !extension(p
, style
).empty();
672 bool is_absolute(const Twine
&path
, Style style
) {
673 SmallString
<128> path_storage
;
674 StringRef p
= path
.toStringRef(path_storage
);
676 bool rootDir
= has_root_directory(p
, style
);
677 bool rootName
= is_style_posix(style
) || has_root_name(p
, style
);
679 return rootDir
&& rootName
;
682 bool is_absolute_gnu(const Twine
&path
, Style style
) {
683 SmallString
<128> path_storage
;
684 StringRef p
= path
.toStringRef(path_storage
);
686 // Handle '/' which is absolute for both Windows and POSIX systems.
687 // Handle '\\' on Windows.
688 if (!p
.empty() && is_separator(p
.front(), style
))
691 if (is_style_windows(style
)) {
692 // Handle drive letter pattern (a character followed by ':') on Windows.
693 if (p
.size() >= 2 && (p
[0] && p
[1] == ':'))
700 bool is_relative(const Twine
&path
, Style style
) {
701 return !is_absolute(path
, style
);
704 StringRef
remove_leading_dotslash(StringRef Path
, Style style
) {
705 // Remove leading "./" (or ".//" or "././" etc.)
706 while (Path
.size() > 2 && Path
[0] == '.' && is_separator(Path
[1], style
)) {
707 Path
= Path
.substr(2);
708 while (Path
.size() > 0 && is_separator(Path
[0], style
))
709 Path
= Path
.substr(1);
714 // Remove path traversal components ("." and "..") when possible, and
715 // canonicalize slashes.
716 bool remove_dots(SmallVectorImpl
<char> &the_path
, bool remove_dot_dot
,
718 style
= real_style(style
);
719 StringRef
remaining(the_path
.data(), the_path
.size());
720 bool needs_change
= false;
721 SmallVector
<StringRef
, 16> components
;
723 // Consume the root path, if present.
724 StringRef root
= path::root_path(remaining
, style
);
725 bool absolute
= !root
.empty();
727 remaining
= remaining
.drop_front(root
.size());
729 // Loop over path components manually. This makes it easier to detect
730 // non-preferred slashes and double separators that must be canonicalized.
731 while (!remaining
.empty()) {
732 size_t next_slash
= remaining
.find_first_of(separators(style
));
733 if (next_slash
== StringRef::npos
)
734 next_slash
= remaining
.size();
735 StringRef component
= remaining
.take_front(next_slash
);
736 remaining
= remaining
.drop_front(next_slash
);
738 // Eat the slash, and check if it is the preferred separator.
739 if (!remaining
.empty()) {
740 needs_change
|= remaining
.front() != preferred_separator(style
);
741 remaining
= remaining
.drop_front();
742 // The path needs to be rewritten if it has a trailing slash.
743 // FIXME: This is emergent behavior that could be removed.
744 needs_change
|= remaining
.empty();
747 // Check for path traversal components or double separators.
748 if (component
.empty() || component
== ".") {
750 } else if (remove_dot_dot
&& component
== "..") {
752 // Do not allow ".." to remove the root component. If this is the
753 // beginning of a relative path, keep the ".." component.
754 if (!components
.empty() && components
.back() != "..") {
755 components
.pop_back();
756 } else if (!absolute
) {
757 components
.push_back(component
);
760 components
.push_back(component
);
764 SmallString
<256> buffer
= root
;
765 // "root" could be "/", which may need to be translated into "\".
766 make_preferred(buffer
, style
);
767 needs_change
|= root
!= buffer
;
769 // Avoid rewriting the path unless we have to.
773 if (!components
.empty()) {
774 buffer
+= components
[0];
775 for (StringRef C
: ArrayRef(components
).drop_front()) {
776 buffer
+= preferred_separator(style
);
780 the_path
.swap(buffer
);
784 } // end namespace path
788 std::error_code
getUniqueID(const Twine Path
, UniqueID
&Result
) {
790 std::error_code EC
= status(Path
, Status
);
793 Result
= Status
.getUniqueID();
794 return std::error_code();
797 void createUniquePath(const Twine
&Model
, SmallVectorImpl
<char> &ResultPath
,
799 SmallString
<128> ModelStorage
;
800 Model
.toVector(ModelStorage
);
803 // Make model absolute by prepending a temp directory if it's not already.
804 if (!sys::path::is_absolute(Twine(ModelStorage
))) {
805 SmallString
<128> TDir
;
806 sys::path::system_temp_directory(true, TDir
);
807 sys::path::append(TDir
, Twine(ModelStorage
));
808 ModelStorage
.swap(TDir
);
812 ResultPath
= ModelStorage
;
813 ResultPath
.push_back(0);
814 ResultPath
.pop_back();
816 // Replace '%' with random chars.
817 for (unsigned i
= 0, e
= ModelStorage
.size(); i
!= e
; ++i
) {
818 if (ModelStorage
[i
] == '%')
819 ResultPath
[i
] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
823 std::error_code
createUniqueFile(const Twine
&Model
, int &ResultFd
,
824 SmallVectorImpl
<char> &ResultPath
,
825 OpenFlags Flags
, unsigned Mode
) {
826 return createUniqueEntity(Model
, ResultFd
, ResultPath
, false, FS_File
, Flags
,
830 std::error_code
createUniqueFile(const Twine
&Model
,
831 SmallVectorImpl
<char> &ResultPath
,
834 auto EC
= createUniqueFile(Model
, FD
, ResultPath
, OF_None
, Mode
);
837 // FD is only needed to avoid race conditions. Close it right away.
842 static std::error_code
843 createTemporaryFile(const Twine
&Model
, int &ResultFD
,
844 llvm::SmallVectorImpl
<char> &ResultPath
, FSEntity Type
,
845 sys::fs::OpenFlags Flags
= sys::fs::OF_None
) {
846 SmallString
<128> Storage
;
847 StringRef P
= Model
.toNullTerminatedStringRef(Storage
);
848 assert(P
.find_first_of(separators(Style::native
)) == StringRef::npos
&&
849 "Model must be a simple filename.");
850 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
851 return createUniqueEntity(P
.begin(), ResultFD
, ResultPath
, true, Type
, Flags
,
852 all_read
| all_write
);
855 static std::error_code
856 createTemporaryFile(const Twine
&Prefix
, StringRef Suffix
, int &ResultFD
,
857 llvm::SmallVectorImpl
<char> &ResultPath
, FSEntity Type
,
858 sys::fs::OpenFlags Flags
= sys::fs::OF_None
) {
859 const char *Middle
= Suffix
.empty() ? "-%%%%%%" : "-%%%%%%.";
860 return createTemporaryFile(Prefix
+ Middle
+ Suffix
, ResultFD
, ResultPath
,
864 std::error_code
createTemporaryFile(const Twine
&Prefix
, StringRef Suffix
,
866 SmallVectorImpl
<char> &ResultPath
,
867 sys::fs::OpenFlags Flags
) {
868 return createTemporaryFile(Prefix
, Suffix
, ResultFD
, ResultPath
, FS_File
,
872 std::error_code
createTemporaryFile(const Twine
&Prefix
, StringRef Suffix
,
873 SmallVectorImpl
<char> &ResultPath
,
874 sys::fs::OpenFlags Flags
) {
876 auto EC
= createTemporaryFile(Prefix
, Suffix
, FD
, ResultPath
, Flags
);
879 // FD is only needed to avoid race conditions. Close it right away.
884 // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
885 // for consistency. We should try using mkdtemp.
886 std::error_code
createUniqueDirectory(const Twine
&Prefix
,
887 SmallVectorImpl
<char> &ResultPath
) {
889 return createUniqueEntity(Prefix
+ "-%%%%%%", Dummy
, ResultPath
, true,
894 getPotentiallyUniqueFileName(const Twine
&Model
,
895 SmallVectorImpl
<char> &ResultPath
) {
897 return createUniqueEntity(Model
, Dummy
, ResultPath
, false, FS_Name
);
901 getPotentiallyUniqueTempFileName(const Twine
&Prefix
, StringRef Suffix
,
902 SmallVectorImpl
<char> &ResultPath
) {
904 return createTemporaryFile(Prefix
, Suffix
, Dummy
, ResultPath
, FS_Name
);
907 void make_absolute(const Twine
¤t_directory
,
908 SmallVectorImpl
<char> &path
) {
909 StringRef
p(path
.data(), path
.size());
911 bool rootDirectory
= path::has_root_directory(p
);
912 bool rootName
= path::has_root_name(p
);
915 if ((rootName
|| is_style_posix(Style::native
)) && rootDirectory
)
918 // All of the following conditions will need the current directory.
919 SmallString
<128> current_dir
;
920 current_directory
.toVector(current_dir
);
922 // Relative path. Prepend the current directory.
923 if (!rootName
&& !rootDirectory
) {
924 // Append path to the current directory.
925 path::append(current_dir
, p
);
926 // Set path to the result.
927 path
.swap(current_dir
);
931 if (!rootName
&& rootDirectory
) {
932 StringRef cdrn
= path::root_name(current_dir
);
933 SmallString
<128> curDirRootName(cdrn
.begin(), cdrn
.end());
934 path::append(curDirRootName
, p
);
935 // Set path to the result.
936 path
.swap(curDirRootName
);
940 if (rootName
&& !rootDirectory
) {
941 StringRef pRootName
= path::root_name(p
);
942 StringRef bRootDirectory
= path::root_directory(current_dir
);
943 StringRef bRelativePath
= path::relative_path(current_dir
);
944 StringRef pRelativePath
= path::relative_path(p
);
946 SmallString
<128> res
;
947 path::append(res
, pRootName
, bRootDirectory
, bRelativePath
, pRelativePath
);
952 llvm_unreachable("All rootName and rootDirectory combinations should have "
956 std::error_code
make_absolute(SmallVectorImpl
<char> &path
) {
957 if (path::is_absolute(path
))
960 SmallString
<128> current_dir
;
961 if (std::error_code ec
= current_path(current_dir
))
964 make_absolute(current_dir
, path
);
968 std::error_code
create_directories(const Twine
&Path
, bool IgnoreExisting
,
970 SmallString
<128> PathStorage
;
971 StringRef P
= Path
.toStringRef(PathStorage
);
973 // Be optimistic and try to create the directory
974 std::error_code EC
= create_directory(P
, IgnoreExisting
, Perms
);
975 // If we succeeded, or had any error other than the parent not existing, just
977 if (EC
!= errc::no_such_file_or_directory
)
980 // We failed because of a no_such_file_or_directory, try to create the
982 StringRef Parent
= path::parent_path(P
);
986 if ((EC
= create_directories(Parent
, IgnoreExisting
, Perms
)))
989 return create_directory(P
, IgnoreExisting
, Perms
);
992 static std::error_code
copy_file_internal(int ReadFD
, int WriteFD
) {
993 const size_t BufSize
= 4096;
994 char *Buf
= new char[BufSize
];
995 int BytesRead
= 0, BytesWritten
= 0;
997 BytesRead
= read(ReadFD
, Buf
, BufSize
);
1001 BytesWritten
= write(WriteFD
, Buf
, BytesRead
);
1002 if (BytesWritten
< 0)
1004 BytesRead
-= BytesWritten
;
1006 if (BytesWritten
< 0)
1011 if (BytesRead
< 0 || BytesWritten
< 0)
1012 return errnoAsErrorCode();
1013 return std::error_code();
1017 std::error_code
copy_file(const Twine
&From
, const Twine
&To
) {
1018 int ReadFD
, WriteFD
;
1019 if (std::error_code EC
= openFileForRead(From
, ReadFD
, OF_None
))
1021 if (std::error_code EC
=
1022 openFileForWrite(To
, WriteFD
, CD_CreateAlways
, OF_None
)) {
1027 std::error_code EC
= copy_file_internal(ReadFD
, WriteFD
);
1036 std::error_code
copy_file(const Twine
&From
, int ToFD
) {
1038 if (std::error_code EC
= openFileForRead(From
, ReadFD
, OF_None
))
1041 std::error_code EC
= copy_file_internal(ReadFD
, ToFD
);
1048 ErrorOr
<MD5::MD5Result
> md5_contents(int FD
) {
1051 constexpr size_t BufSize
= 4096;
1052 std::vector
<uint8_t> Buf(BufSize
);
1055 BytesRead
= read(FD
, Buf
.data(), BufSize
);
1058 Hash
.update(ArrayRef(Buf
.data(), BytesRead
));
1062 return errnoAsErrorCode();
1063 MD5::MD5Result Result
;
1068 ErrorOr
<MD5::MD5Result
> md5_contents(const Twine
&Path
) {
1070 if (auto EC
= openFileForRead(Path
, FD
, OF_None
))
1073 auto Result
= md5_contents(FD
);
1078 bool exists(const basic_file_status
&status
) {
1079 return status_known(status
) && status
.type() != file_type::file_not_found
;
1082 bool status_known(const basic_file_status
&s
) {
1083 return s
.type() != file_type::status_error
;
1086 file_type
get_file_type(const Twine
&Path
, bool Follow
) {
1088 if (status(Path
, st
, Follow
))
1089 return file_type::status_error
;
1093 bool is_directory(const basic_file_status
&status
) {
1094 return status
.type() == file_type::directory_file
;
1097 std::error_code
is_directory(const Twine
&path
, bool &result
) {
1099 if (std::error_code ec
= status(path
, st
))
1101 result
= is_directory(st
);
1102 return std::error_code();
1105 bool is_regular_file(const basic_file_status
&status
) {
1106 return status
.type() == file_type::regular_file
;
1109 std::error_code
is_regular_file(const Twine
&path
, bool &result
) {
1111 if (std::error_code ec
= status(path
, st
))
1113 result
= is_regular_file(st
);
1114 return std::error_code();
1117 bool is_symlink_file(const basic_file_status
&status
) {
1118 return status
.type() == file_type::symlink_file
;
1121 std::error_code
is_symlink_file(const Twine
&path
, bool &result
) {
1123 if (std::error_code ec
= status(path
, st
, false))
1125 result
= is_symlink_file(st
);
1126 return std::error_code();
1129 bool is_other(const basic_file_status
&status
) {
1130 return exists(status
) &&
1131 !is_regular_file(status
) &&
1132 !is_directory(status
);
1135 std::error_code
is_other(const Twine
&Path
, bool &Result
) {
1136 file_status FileStatus
;
1137 if (std::error_code EC
= status(Path
, FileStatus
))
1139 Result
= is_other(FileStatus
);
1140 return std::error_code();
1143 void directory_entry::replace_filename(const Twine
&Filename
, file_type Type
,
1144 basic_file_status Status
) {
1145 SmallString
<128> PathStr
= path::parent_path(Path
);
1146 path::append(PathStr
, Filename
);
1147 this->Path
= std::string(PathStr
);
1149 this->Status
= Status
;
1152 ErrorOr
<perms
> getPermissions(const Twine
&Path
) {
1154 if (std::error_code EC
= status(Path
, Status
))
1157 return Status
.permissions();
1160 size_t mapped_file_region::size() const {
1161 assert(Mapping
&& "Mapping failed but used anyway!");
1165 char *mapped_file_region::data() const {
1166 assert(Mapping
&& "Mapping failed but used anyway!");
1167 return reinterpret_cast<char *>(Mapping
);
1170 const char *mapped_file_region::const_data() const {
1171 assert(Mapping
&& "Mapping failed but used anyway!");
1172 return reinterpret_cast<const char *>(Mapping
);
1175 Error
readNativeFileToEOF(file_t FileHandle
, SmallVectorImpl
<char> &Buffer
,
1176 ssize_t ChunkSize
) {
1177 // Install a handler to truncate the buffer to the correct size on exit.
1178 size_t Size
= Buffer
.size();
1179 auto TruncateOnExit
= make_scope_exit([&]() { Buffer
.truncate(Size
); });
1181 // Read into Buffer until we hit EOF.
1183 Buffer
.resize_for_overwrite(Size
+ ChunkSize
);
1184 Expected
<size_t> ReadBytes
= readNativeFile(
1185 FileHandle
, MutableArrayRef(Buffer
.begin() + Size
, ChunkSize
));
1187 return ReadBytes
.takeError();
1188 if (*ReadBytes
== 0)
1189 return Error::success();
1194 } // end namespace fs
1195 } // end namespace sys
1196 } // end namespace llvm
1198 // Include the truly platform-specific parts.
1199 #if defined(LLVM_ON_UNIX)
1200 #include "Unix/Path.inc"
1203 #include "Windows/Path.inc"
1210 TempFile::TempFile(StringRef Name
, int FD
)
1211 : TmpName(std::string(Name
)), FD(FD
) {}
1212 TempFile::TempFile(TempFile
&&Other
) { *this = std::move(Other
); }
1213 TempFile
&TempFile::operator=(TempFile
&&Other
) {
1214 TmpName
= std::move(Other
.TmpName
);
1219 RemoveOnClose
= Other
.RemoveOnClose
;
1220 Other
.RemoveOnClose
= false;
1225 TempFile::~TempFile() { assert(Done
); }
1227 Error
TempFile::discard() {
1229 if (FD
!= -1 && close(FD
) == -1) {
1230 std::error_code EC
= errnoAsErrorCode();
1231 return errorCodeToError(EC
);
1236 // On Windows, closing will remove the file, if we set the delete
1237 // disposition. If not, remove it manually.
1238 bool Remove
= RemoveOnClose
;
1240 // Always try to remove the file.
1243 std::error_code RemoveEC
;
1244 if (Remove
&& !TmpName
.empty()) {
1245 RemoveEC
= fs::remove(TmpName
);
1246 sys::DontRemoveFileOnSignal(TmpName
);
1252 return errorCodeToError(RemoveEC
);
1255 Error
TempFile::keep(const Twine
&Name
) {
1258 // Always try to close and rename.
1260 // If we can't cancel the delete don't rename.
1261 auto H
= reinterpret_cast<HANDLE
>(_get_osfhandle(FD
));
1262 std::error_code RenameEC
=
1263 RemoveOnClose
? std::error_code() : setDeleteDisposition(H
, false);
1264 bool ShouldDelete
= false;
1266 RenameEC
= rename_handle(H
, Name
);
1267 // If rename failed because it's cross-device, copy instead
1269 std::error_code(ERROR_NOT_SAME_DEVICE
, std::system_category())) {
1270 RenameEC
= copy_file(TmpName
, Name
);
1271 ShouldDelete
= true;
1275 // If we can't rename or copy, discard the temporary file.
1277 ShouldDelete
= true;
1280 setDeleteDisposition(H
, true);
1285 std::error_code RenameEC
= fs::rename(TmpName
, Name
);
1287 // If we can't rename, try to copy to work around cross-device link issues.
1288 RenameEC
= sys::fs::copy_file(TmpName
, Name
);
1289 // If we can't rename or copy, discard the temporary file.
1294 sys::DontRemoveFileOnSignal(TmpName
);
1299 if (close(FD
) == -1)
1300 return errorCodeToError(errnoAsErrorCode());
1303 return errorCodeToError(RenameEC
);
1306 Error
TempFile::keep() {
1311 auto H
= reinterpret_cast<HANDLE
>(_get_osfhandle(FD
));
1312 if (std::error_code EC
= setDeleteDisposition(H
, false))
1313 return errorCodeToError(EC
);
1315 sys::DontRemoveFileOnSignal(TmpName
);
1319 if (close(FD
) == -1)
1320 return errorCodeToError(errnoAsErrorCode());
1323 return Error::success();
1326 Expected
<TempFile
> TempFile::create(const Twine
&Model
, unsigned Mode
,
1327 OpenFlags ExtraFlags
) {
1329 SmallString
<128> ResultPath
;
1330 if (std::error_code EC
=
1331 createUniqueFile(Model
, FD
, ResultPath
, OF_Delete
| ExtraFlags
, Mode
))
1332 return errorCodeToError(EC
);
1334 TempFile
Ret(ResultPath
, FD
);
1336 auto H
= reinterpret_cast<HANDLE
>(_get_osfhandle(FD
));
1337 bool SetSignalHandler
= false;
1338 if (std::error_code EC
= setDeleteDisposition(H
, true)) {
1339 Ret
.RemoveOnClose
= true;
1340 SetSignalHandler
= true;
1343 bool SetSignalHandler
= true;
1345 if (SetSignalHandler
&& sys::RemoveFileOnSignal(ResultPath
)) {
1346 // Make sure we delete the file when RemoveFileOnSignal fails.
1347 consumeError(Ret
.discard());
1348 std::error_code
EC(errc::operation_not_permitted
);
1349 return errorCodeToError(EC
);
1351 return std::move(Ret
);