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/Errc.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/Process.h"
23 #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
) {
41 if (style
!= Style::native
)
43 if (is_style_posix(style
))
45 return LLVM_WINDOWS_PREFER_FORWARD_SLASH
? Style::windows_slash
46 : Style::windows_backslash
;
49 inline const char *separators(Style style
) {
50 if (is_style_windows(style
))
55 inline char preferred_separator(Style style
) {
56 if (real_style(style
) == Style::windows
)
61 StringRef
find_first_component(StringRef path
, Style style
) {
62 // Look for this first component in the following order.
63 // * empty (in this case we return an empty string)
64 // * either C: or {//,\\}net.
66 // * {file,directory}name
71 if (is_style_windows(style
)) {
73 if (path
.size() >= 2 &&
74 std::isalpha(static_cast<unsigned char>(path
[0])) && path
[1] == ':')
75 return path
.substr(0, 2);
79 if ((path
.size() > 2) && is_separator(path
[0], style
) &&
80 path
[0] == path
[1] && !is_separator(path
[2], style
)) {
81 // Find the next directory separator.
82 size_t end
= path
.find_first_of(separators(style
), 2);
83 return path
.substr(0, end
);
87 if (is_separator(path
[0], style
))
88 return path
.substr(0, 1);
90 // * {file,directory}name
91 size_t end
= path
.find_first_of(separators(style
));
92 return path
.substr(0, end
);
95 // Returns the first character of the filename in str. For paths ending in
96 // '/', it returns the position of the '/'.
97 size_t filename_pos(StringRef str
, Style style
) {
98 if (str
.size() > 0 && is_separator(str
[str
.size() - 1], style
))
99 return str
.size() - 1;
101 size_t pos
= str
.find_last_of(separators(style
), str
.size() - 1);
103 if (is_style_windows(style
)) {
104 if (pos
== StringRef::npos
)
105 pos
= str
.find_last_of(':', str
.size() - 1);
108 if (pos
== StringRef::npos
|| (pos
== 1 && is_separator(str
[0], style
)))
114 // Returns the position of the root directory in str. If there is no root
115 // directory in str, it returns StringRef::npos.
116 size_t root_dir_start(StringRef str
, Style style
) {
118 if (is_style_windows(style
)) {
119 if (str
.size() > 2 && str
[1] == ':' && is_separator(str
[2], style
))
124 if (str
.size() > 3 && is_separator(str
[0], style
) && str
[0] == str
[1] &&
125 !is_separator(str
[2], style
)) {
126 return str
.find_first_of(separators(style
), 2);
130 if (str
.size() > 0 && is_separator(str
[0], style
))
133 return StringRef::npos
;
136 // Returns the position past the end of the "parent path" of path. The parent
137 // path will not end in '/', unless the parent is the root directory. If the
138 // path has no parent, 0 is returned.
139 size_t parent_path_end(StringRef path
, Style style
) {
140 size_t end_pos
= filename_pos(path
, style
);
142 bool filename_was_sep
=
143 path
.size() > 0 && is_separator(path
[end_pos
], style
);
145 // Skip separators until we reach root dir (or the start of the string).
146 size_t root_dir_pos
= root_dir_start(path
, style
);
147 while (end_pos
> 0 &&
148 (root_dir_pos
== StringRef::npos
|| end_pos
> root_dir_pos
) &&
149 is_separator(path
[end_pos
- 1], style
))
152 if (end_pos
== root_dir_pos
&& !filename_was_sep
) {
153 // We've reached the root dir and the input path was *not* ending in a
154 // sequence of slashes. Include the root dir in the parent path.
155 return root_dir_pos
+ 1;
158 // Otherwise, just include before the last slash.
161 } // end unnamed namespace
169 static std::error_code
170 createUniqueEntity(const Twine
&Model
, int &ResultFD
,
171 SmallVectorImpl
<char> &ResultPath
, bool MakeAbsolute
,
172 FSEntity Type
, sys::fs::OpenFlags Flags
= sys::fs::OF_None
,
175 // Limit the number of attempts we make, so that we don't infinite loop. E.g.
176 // "permission denied" could be for a specific file (so we retry with a
177 // different name) or for the whole directory (retry would always fail).
178 // Checking which is racy, so we try a number of times, then give up.
180 for (int Retries
= 128; Retries
> 0; --Retries
) {
181 sys::fs::createUniquePath(Model
, ResultPath
, MakeAbsolute
);
182 // Try to open + create the file.
185 EC
= sys::fs::openFileForReadWrite(Twine(ResultPath
.begin()), ResultFD
,
186 sys::fs::CD_CreateNew
, Flags
, Mode
);
188 // errc::permission_denied happens on Windows when we try to open a file
189 // that has been marked for deletion.
190 if (EC
== errc::file_exists
|| EC
== errc::permission_denied
)
195 return std::error_code();
199 EC
= sys::fs::access(ResultPath
.begin(), sys::fs::AccessMode::Exist
);
200 if (EC
== errc::no_such_file_or_directory
)
201 return std::error_code();
208 EC
= sys::fs::create_directory(ResultPath
.begin(), false);
210 if (EC
== errc::file_exists
)
214 return std::error_code();
217 llvm_unreachable("Invalid Type");
226 const_iterator
begin(StringRef path
, Style style
) {
229 i
.Component
= find_first_component(path
, style
);
235 const_iterator
end(StringRef path
) {
238 i
.Position
= path
.size();
242 const_iterator
&const_iterator::operator++() {
243 assert(Position
< Path
.size() && "Tried to increment past end!");
245 // Increment Position to past the current component
246 Position
+= Component
.size();
249 if (Position
== Path
.size()) {
250 Component
= StringRef();
254 // Both POSIX and Windows treat paths that begin with exactly two separators
256 bool was_net
= Component
.size() > 2 && is_separator(Component
[0], S
) &&
257 Component
[1] == Component
[0] && !is_separator(Component
[2], S
);
259 // Handle separators.
260 if (is_separator(Path
[Position
], S
)) {
264 (is_style_windows(S
) && Component
.ends_with(":"))) {
265 Component
= Path
.substr(Position
, 1);
269 // Skip extra separators.
270 while (Position
!= Path
.size() && is_separator(Path
[Position
], S
)) {
274 // Treat trailing '/' as a '.', unless it is the root dir.
275 if (Position
== Path
.size() && Component
!= "/") {
282 // Find next component.
283 size_t end_pos
= Path
.find_first_of(separators(S
), Position
);
284 Component
= Path
.slice(Position
, end_pos
);
289 bool const_iterator::operator==(const const_iterator
&RHS
) const {
290 return Path
.begin() == RHS
.Path
.begin() && Position
== RHS
.Position
;
293 ptrdiff_t const_iterator::operator-(const const_iterator
&RHS
) const {
294 return Position
- RHS
.Position
;
297 reverse_iterator
rbegin(StringRef Path
, Style style
) {
300 I
.Position
= Path
.size();
306 reverse_iterator
rend(StringRef Path
) {
309 I
.Component
= Path
.substr(0, 0);
314 reverse_iterator
&reverse_iterator::operator++() {
315 size_t root_dir_pos
= root_dir_start(Path
, S
);
317 // Skip separators unless it's the root directory.
318 size_t end_pos
= Position
;
319 while (end_pos
> 0 && (end_pos
- 1) != root_dir_pos
&&
320 is_separator(Path
[end_pos
- 1], S
))
323 // Treat trailing '/' as a '.', unless it is the root dir.
324 if (Position
== Path
.size() && !Path
.empty() &&
325 is_separator(Path
.back(), S
) &&
326 (root_dir_pos
== StringRef::npos
|| end_pos
- 1 > root_dir_pos
)) {
332 // Find next separator.
333 size_t start_pos
= filename_pos(Path
.substr(0, end_pos
), S
);
334 Component
= Path
.slice(start_pos
, end_pos
);
335 Position
= start_pos
;
339 bool reverse_iterator::operator==(const reverse_iterator
&RHS
) const {
340 return Path
.begin() == RHS
.Path
.begin() && Component
== RHS
.Component
&&
341 Position
== RHS
.Position
;
344 ptrdiff_t reverse_iterator::operator-(const reverse_iterator
&RHS
) const {
345 return Position
- RHS
.Position
;
348 StringRef
root_path(StringRef path
, Style style
) {
349 const_iterator b
= begin(path
, style
), pos
= b
, e
= end(path
);
352 b
->size() > 2 && is_separator((*b
)[0], style
) && (*b
)[1] == (*b
)[0];
353 bool has_drive
= is_style_windows(style
) && b
->ends_with(":");
355 if (has_net
|| has_drive
) {
356 if ((++pos
!= e
) && is_separator((*pos
)[0], style
)) {
357 // {C:/,//net/}, so get the first two components.
358 return path
.substr(0, b
->size() + pos
->size());
360 // just {C:,//net}, return the first component.
364 // POSIX style root directory.
365 if (is_separator((*b
)[0], style
)) {
373 StringRef
root_name(StringRef path
, Style style
) {
374 const_iterator b
= begin(path
, style
), e
= end(path
);
377 b
->size() > 2 && is_separator((*b
)[0], style
) && (*b
)[1] == (*b
)[0];
378 bool has_drive
= is_style_windows(style
) && b
->ends_with(":");
380 if (has_net
|| has_drive
) {
381 // just {C:,//net}, return the first component.
386 // No path or no name.
390 StringRef
root_directory(StringRef path
, Style style
) {
391 const_iterator b
= begin(path
, style
), pos
= b
, e
= end(path
);
394 b
->size() > 2 && is_separator((*b
)[0], style
) && (*b
)[1] == (*b
)[0];
395 bool has_drive
= is_style_windows(style
) && b
->ends_with(":");
397 if ((has_net
|| has_drive
) &&
398 // {C:,//net}, skip to the next component.
399 (++pos
!= e
) && is_separator((*pos
)[0], style
)) {
403 // POSIX style root directory.
404 if (!has_net
&& is_separator((*b
)[0], style
)) {
409 // No path or no root.
413 StringRef
relative_path(StringRef path
, Style style
) {
414 StringRef root
= root_path(path
, style
);
415 return path
.substr(root
.size());
418 void append(SmallVectorImpl
<char> &path
, Style style
, const Twine
&a
,
419 const Twine
&b
, const Twine
&c
, const Twine
&d
) {
420 SmallString
<32> a_storage
;
421 SmallString
<32> b_storage
;
422 SmallString
<32> c_storage
;
423 SmallString
<32> d_storage
;
425 SmallVector
<StringRef
, 4> components
;
426 if (!a
.isTriviallyEmpty()) components
.push_back(a
.toStringRef(a_storage
));
427 if (!b
.isTriviallyEmpty()) components
.push_back(b
.toStringRef(b_storage
));
428 if (!c
.isTriviallyEmpty()) components
.push_back(c
.toStringRef(c_storage
));
429 if (!d
.isTriviallyEmpty()) components
.push_back(d
.toStringRef(d_storage
));
431 for (auto &component
: components
) {
433 !path
.empty() && is_separator(path
[path
.size() - 1], style
);
435 // Strip separators from beginning of component.
436 size_t loc
= component
.find_first_not_of(separators(style
));
437 StringRef c
= component
.substr(loc
);
440 path
.append(c
.begin(), c
.end());
444 bool component_has_sep
=
445 !component
.empty() && is_separator(component
[0], style
);
446 if (!component_has_sep
&&
447 !(path
.empty() || has_root_name(component
, style
))) {
449 path
.push_back(preferred_separator(style
));
452 path
.append(component
.begin(), component
.end());
456 void append(SmallVectorImpl
<char> &path
, const Twine
&a
, const Twine
&b
,
457 const Twine
&c
, const Twine
&d
) {
458 append(path
, Style::native
, a
, b
, c
, d
);
461 void append(SmallVectorImpl
<char> &path
, const_iterator begin
,
462 const_iterator end
, Style style
) {
463 for (; begin
!= end
; ++begin
)
464 path::append(path
, style
, *begin
);
467 StringRef
parent_path(StringRef path
, Style style
) {
468 size_t end_pos
= parent_path_end(path
, style
);
469 if (end_pos
== StringRef::npos
)
471 return path
.substr(0, end_pos
);
474 void remove_filename(SmallVectorImpl
<char> &path
, Style style
) {
475 size_t end_pos
= parent_path_end(StringRef(path
.begin(), path
.size()), style
);
476 if (end_pos
!= StringRef::npos
)
477 path
.truncate(end_pos
);
480 void replace_extension(SmallVectorImpl
<char> &path
, const Twine
&extension
,
482 StringRef
p(path
.begin(), path
.size());
483 SmallString
<32> ext_storage
;
484 StringRef ext
= extension
.toStringRef(ext_storage
);
486 // Erase existing extension.
487 size_t pos
= p
.find_last_of('.');
488 if (pos
!= StringRef::npos
&& pos
>= filename_pos(p
, style
))
491 // Append '.' if needed.
492 if (ext
.size() > 0 && ext
[0] != '.')
496 path
.append(ext
.begin(), ext
.end());
499 static bool starts_with(StringRef Path
, StringRef Prefix
,
500 Style style
= Style::native
) {
501 // Windows prefix matching : case and separator insensitive
502 if (is_style_windows(style
)) {
503 if (Path
.size() < Prefix
.size())
505 for (size_t I
= 0, E
= Prefix
.size(); I
!= E
; ++I
) {
506 bool SepPath
= is_separator(Path
[I
], style
);
507 bool SepPrefix
= is_separator(Prefix
[I
], style
);
508 if (SepPath
!= SepPrefix
)
510 if (!SepPath
&& toLower(Path
[I
]) != toLower(Prefix
[I
]))
515 return Path
.starts_with(Prefix
);
518 bool replace_path_prefix(SmallVectorImpl
<char> &Path
, StringRef OldPrefix
,
519 StringRef NewPrefix
, Style style
) {
520 if (OldPrefix
.empty() && NewPrefix
.empty())
523 StringRef
OrigPath(Path
.begin(), Path
.size());
524 if (!starts_with(OrigPath
, OldPrefix
, style
))
527 // If prefixes have the same size we can simply copy the new one over.
528 if (OldPrefix
.size() == NewPrefix
.size()) {
529 llvm::copy(NewPrefix
, Path
.begin());
533 StringRef RelPath
= OrigPath
.substr(OldPrefix
.size());
534 SmallString
<256> NewPath
;
535 (Twine(NewPrefix
) + RelPath
).toVector(NewPath
);
540 void native(const Twine
&path
, SmallVectorImpl
<char> &result
, Style style
) {
541 assert((!path
.isSingleStringRef() ||
542 path
.getSingleStringRef().data() != result
.data()) &&
543 "path and result are not allowed to overlap!");
546 path
.toVector(result
);
547 native(result
, style
);
550 void native(SmallVectorImpl
<char> &Path
, Style style
) {
553 if (is_style_windows(style
)) {
554 for (char &Ch
: Path
)
555 if (is_separator(Ch
, style
))
556 Ch
= preferred_separator(style
);
557 if (Path
[0] == '~' && (Path
.size() == 1 || is_separator(Path
[1], style
))) {
558 SmallString
<128> PathHome
;
559 home_directory(PathHome
);
560 PathHome
.append(Path
.begin() + 1, Path
.end());
564 std::replace(Path
.begin(), Path
.end(), '\\', '/');
568 std::string
convert_to_slash(StringRef path
, Style style
) {
569 if (is_style_posix(style
))
570 return std::string(path
);
572 std::string s
= path
.str();
573 std::replace(s
.begin(), s
.end(), '\\', '/');
577 StringRef
filename(StringRef path
, Style style
) { return *rbegin(path
, style
); }
579 StringRef
stem(StringRef path
, Style style
) {
580 StringRef fname
= filename(path
, style
);
581 size_t pos
= fname
.find_last_of('.');
582 if (pos
== StringRef::npos
)
584 if ((fname
.size() == 1 && fname
== ".") ||
585 (fname
.size() == 2 && fname
== ".."))
587 return fname
.substr(0, pos
);
590 StringRef
extension(StringRef path
, Style style
) {
591 StringRef fname
= filename(path
, style
);
592 size_t pos
= fname
.find_last_of('.');
593 if (pos
== StringRef::npos
)
595 if ((fname
.size() == 1 && fname
== ".") ||
596 (fname
.size() == 2 && fname
== ".."))
598 return fname
.substr(pos
);
601 bool is_separator(char value
, Style style
) {
604 if (is_style_windows(style
))
605 return value
== '\\';
609 StringRef
get_separator(Style style
) {
610 if (real_style(style
) == Style::windows
)
615 bool has_root_name(const Twine
&path
, Style style
) {
616 SmallString
<128> path_storage
;
617 StringRef p
= path
.toStringRef(path_storage
);
619 return !root_name(p
, style
).empty();
622 bool has_root_directory(const Twine
&path
, Style style
) {
623 SmallString
<128> path_storage
;
624 StringRef p
= path
.toStringRef(path_storage
);
626 return !root_directory(p
, style
).empty();
629 bool has_root_path(const Twine
&path
, Style style
) {
630 SmallString
<128> path_storage
;
631 StringRef p
= path
.toStringRef(path_storage
);
633 return !root_path(p
, style
).empty();
636 bool has_relative_path(const Twine
&path
, Style style
) {
637 SmallString
<128> path_storage
;
638 StringRef p
= path
.toStringRef(path_storage
);
640 return !relative_path(p
, style
).empty();
643 bool has_filename(const Twine
&path
, Style style
) {
644 SmallString
<128> path_storage
;
645 StringRef p
= path
.toStringRef(path_storage
);
647 return !filename(p
, style
).empty();
650 bool has_parent_path(const Twine
&path
, Style style
) {
651 SmallString
<128> path_storage
;
652 StringRef p
= path
.toStringRef(path_storage
);
654 return !parent_path(p
, style
).empty();
657 bool has_stem(const Twine
&path
, Style style
) {
658 SmallString
<128> path_storage
;
659 StringRef p
= path
.toStringRef(path_storage
);
661 return !stem(p
, style
).empty();
664 bool has_extension(const Twine
&path
, Style style
) {
665 SmallString
<128> path_storage
;
666 StringRef p
= path
.toStringRef(path_storage
);
668 return !extension(p
, style
).empty();
671 bool is_absolute(const Twine
&path
, Style style
) {
672 SmallString
<128> path_storage
;
673 StringRef p
= path
.toStringRef(path_storage
);
675 bool rootDir
= has_root_directory(p
, style
);
676 bool rootName
= is_style_posix(style
) || has_root_name(p
, style
);
678 return rootDir
&& rootName
;
681 bool is_absolute_gnu(const Twine
&path
, Style style
) {
682 SmallString
<128> path_storage
;
683 StringRef p
= path
.toStringRef(path_storage
);
685 // Handle '/' which is absolute for both Windows and POSIX systems.
686 // Handle '\\' on Windows.
687 if (!p
.empty() && is_separator(p
.front(), style
))
690 if (is_style_windows(style
)) {
691 // Handle drive letter pattern (a character followed by ':') on Windows.
692 if (p
.size() >= 2 && (p
[0] && p
[1] == ':'))
699 bool is_relative(const Twine
&path
, Style style
) {
700 return !is_absolute(path
, style
);
703 StringRef
remove_leading_dotslash(StringRef Path
, Style style
) {
704 // Remove leading "./" (or ".//" or "././" etc.)
705 while (Path
.size() > 2 && Path
[0] == '.' && is_separator(Path
[1], style
)) {
706 Path
= Path
.substr(2);
707 while (Path
.size() > 0 && is_separator(Path
[0], style
))
708 Path
= Path
.substr(1);
713 // Remove path traversal components ("." and "..") when possible, and
714 // canonicalize slashes.
715 bool remove_dots(SmallVectorImpl
<char> &the_path
, bool remove_dot_dot
,
717 style
= real_style(style
);
718 StringRef
remaining(the_path
.data(), the_path
.size());
719 bool needs_change
= false;
720 SmallVector
<StringRef
, 16> components
;
722 // Consume the root path, if present.
723 StringRef root
= path::root_path(remaining
, style
);
724 bool absolute
= !root
.empty();
726 remaining
= remaining
.drop_front(root
.size());
728 // Loop over path components manually. This makes it easier to detect
729 // non-preferred slashes and double separators that must be canonicalized.
730 while (!remaining
.empty()) {
731 size_t next_slash
= remaining
.find_first_of(separators(style
));
732 if (next_slash
== StringRef::npos
)
733 next_slash
= remaining
.size();
734 StringRef component
= remaining
.take_front(next_slash
);
735 remaining
= remaining
.drop_front(next_slash
);
737 // Eat the slash, and check if it is the preferred separator.
738 if (!remaining
.empty()) {
739 needs_change
|= remaining
.front() != preferred_separator(style
);
740 remaining
= remaining
.drop_front();
741 // The path needs to be rewritten if it has a trailing slash.
742 // FIXME: This is emergent behavior that could be removed.
743 needs_change
|= remaining
.empty();
746 // Check for path traversal components or double separators.
747 if (component
.empty() || component
== ".") {
749 } else if (remove_dot_dot
&& component
== "..") {
751 // Do not allow ".." to remove the root component. If this is the
752 // beginning of a relative path, keep the ".." component.
753 if (!components
.empty() && components
.back() != "..") {
754 components
.pop_back();
755 } else if (!absolute
) {
756 components
.push_back(component
);
759 components
.push_back(component
);
763 SmallString
<256> buffer
= root
;
764 // "root" could be "/", which may need to be translated into "\".
765 make_preferred(buffer
, style
);
766 needs_change
|= root
!= buffer
;
768 // Avoid rewriting the path unless we have to.
772 if (!components
.empty()) {
773 buffer
+= components
[0];
774 for (StringRef C
: ArrayRef(components
).drop_front()) {
775 buffer
+= preferred_separator(style
);
779 the_path
.swap(buffer
);
783 } // end namespace path
787 std::error_code
getUniqueID(const Twine Path
, UniqueID
&Result
) {
789 std::error_code EC
= status(Path
, Status
);
792 Result
= Status
.getUniqueID();
793 return std::error_code();
796 void createUniquePath(const Twine
&Model
, SmallVectorImpl
<char> &ResultPath
,
798 SmallString
<128> ModelStorage
;
799 Model
.toVector(ModelStorage
);
802 // Make model absolute by prepending a temp directory if it's not already.
803 if (!sys::path::is_absolute(Twine(ModelStorage
))) {
804 SmallString
<128> TDir
;
805 sys::path::system_temp_directory(true, TDir
);
806 sys::path::append(TDir
, Twine(ModelStorage
));
807 ModelStorage
.swap(TDir
);
811 ResultPath
= ModelStorage
;
812 ResultPath
.push_back(0);
813 ResultPath
.pop_back();
815 // Replace '%' with random chars.
816 for (unsigned i
= 0, e
= ModelStorage
.size(); i
!= e
; ++i
) {
817 if (ModelStorage
[i
] == '%')
818 ResultPath
[i
] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
822 std::error_code
createUniqueFile(const Twine
&Model
, int &ResultFd
,
823 SmallVectorImpl
<char> &ResultPath
,
824 OpenFlags Flags
, unsigned Mode
) {
825 return createUniqueEntity(Model
, ResultFd
, ResultPath
, false, FS_File
, Flags
,
829 std::error_code
createUniqueFile(const Twine
&Model
,
830 SmallVectorImpl
<char> &ResultPath
,
833 auto EC
= createUniqueFile(Model
, FD
, ResultPath
, OF_None
, Mode
);
836 // FD is only needed to avoid race conditions. Close it right away.
841 static std::error_code
842 createTemporaryFile(const Twine
&Model
, int &ResultFD
,
843 llvm::SmallVectorImpl
<char> &ResultPath
, FSEntity Type
,
844 sys::fs::OpenFlags Flags
= sys::fs::OF_None
) {
845 SmallString
<128> Storage
;
846 StringRef P
= Model
.toNullTerminatedStringRef(Storage
);
847 assert(P
.find_first_of(separators(Style::native
)) == StringRef::npos
&&
848 "Model must be a simple filename.");
849 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
850 return createUniqueEntity(P
.begin(), ResultFD
, ResultPath
, true, Type
, Flags
,
851 all_read
| all_write
);
854 static std::error_code
855 createTemporaryFile(const Twine
&Prefix
, StringRef Suffix
, int &ResultFD
,
856 llvm::SmallVectorImpl
<char> &ResultPath
, FSEntity Type
,
857 sys::fs::OpenFlags Flags
= sys::fs::OF_None
) {
858 const char *Middle
= Suffix
.empty() ? "-%%%%%%" : "-%%%%%%.";
859 return createTemporaryFile(Prefix
+ Middle
+ Suffix
, ResultFD
, ResultPath
,
863 std::error_code
createTemporaryFile(const Twine
&Prefix
, StringRef Suffix
,
865 SmallVectorImpl
<char> &ResultPath
,
866 sys::fs::OpenFlags Flags
) {
867 return createTemporaryFile(Prefix
, Suffix
, ResultFD
, ResultPath
, FS_File
,
871 std::error_code
createTemporaryFile(const Twine
&Prefix
, StringRef Suffix
,
872 SmallVectorImpl
<char> &ResultPath
,
873 sys::fs::OpenFlags Flags
) {
875 auto EC
= createTemporaryFile(Prefix
, Suffix
, FD
, ResultPath
, Flags
);
878 // FD is only needed to avoid race conditions. Close it right away.
883 // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
884 // for consistency. We should try using mkdtemp.
885 std::error_code
createUniqueDirectory(const Twine
&Prefix
,
886 SmallVectorImpl
<char> &ResultPath
) {
888 return createUniqueEntity(Prefix
+ "-%%%%%%", Dummy
, ResultPath
, true,
893 getPotentiallyUniqueFileName(const Twine
&Model
,
894 SmallVectorImpl
<char> &ResultPath
) {
896 return createUniqueEntity(Model
, Dummy
, ResultPath
, false, FS_Name
);
900 getPotentiallyUniqueTempFileName(const Twine
&Prefix
, StringRef Suffix
,
901 SmallVectorImpl
<char> &ResultPath
) {
903 return createTemporaryFile(Prefix
, Suffix
, Dummy
, ResultPath
, FS_Name
);
906 void make_absolute(const Twine
¤t_directory
,
907 SmallVectorImpl
<char> &path
) {
908 StringRef
p(path
.data(), path
.size());
910 bool rootDirectory
= path::has_root_directory(p
);
911 bool rootName
= path::has_root_name(p
);
914 if ((rootName
|| is_style_posix(Style::native
)) && rootDirectory
)
917 // All of the following conditions will need the current directory.
918 SmallString
<128> current_dir
;
919 current_directory
.toVector(current_dir
);
921 // Relative path. Prepend the current directory.
922 if (!rootName
&& !rootDirectory
) {
923 // Append path to the current directory.
924 path::append(current_dir
, p
);
925 // Set path to the result.
926 path
.swap(current_dir
);
930 if (!rootName
&& rootDirectory
) {
931 StringRef cdrn
= path::root_name(current_dir
);
932 SmallString
<128> curDirRootName(cdrn
.begin(), cdrn
.end());
933 path::append(curDirRootName
, p
);
934 // Set path to the result.
935 path
.swap(curDirRootName
);
939 if (rootName
&& !rootDirectory
) {
940 StringRef pRootName
= path::root_name(p
);
941 StringRef bRootDirectory
= path::root_directory(current_dir
);
942 StringRef bRelativePath
= path::relative_path(current_dir
);
943 StringRef pRelativePath
= path::relative_path(p
);
945 SmallString
<128> res
;
946 path::append(res
, pRootName
, bRootDirectory
, bRelativePath
, pRelativePath
);
951 llvm_unreachable("All rootName and rootDirectory combinations should have "
955 std::error_code
make_absolute(SmallVectorImpl
<char> &path
) {
956 if (path::is_absolute(path
))
959 SmallString
<128> current_dir
;
960 if (std::error_code ec
= current_path(current_dir
))
963 make_absolute(current_dir
, path
);
967 std::error_code
create_directories(const Twine
&Path
, bool IgnoreExisting
,
969 SmallString
<128> PathStorage
;
970 StringRef P
= Path
.toStringRef(PathStorage
);
972 // Be optimistic and try to create the directory
973 std::error_code EC
= create_directory(P
, IgnoreExisting
, Perms
);
974 // If we succeeded, or had any error other than the parent not existing, just
976 if (EC
!= errc::no_such_file_or_directory
)
979 // We failed because of a no_such_file_or_directory, try to create the
981 StringRef Parent
= path::parent_path(P
);
985 if ((EC
= create_directories(Parent
, IgnoreExisting
, Perms
)))
988 return create_directory(P
, IgnoreExisting
, Perms
);
991 static std::error_code
copy_file_internal(int ReadFD
, int WriteFD
) {
992 const size_t BufSize
= 4096;
993 char *Buf
= new char[BufSize
];
994 int BytesRead
= 0, BytesWritten
= 0;
996 BytesRead
= read(ReadFD
, Buf
, BufSize
);
1000 BytesWritten
= write(WriteFD
, Buf
, BytesRead
);
1001 if (BytesWritten
< 0)
1003 BytesRead
-= BytesWritten
;
1005 if (BytesWritten
< 0)
1010 if (BytesRead
< 0 || BytesWritten
< 0)
1011 return errnoAsErrorCode();
1012 return std::error_code();
1016 std::error_code
copy_file(const Twine
&From
, const Twine
&To
) {
1017 int ReadFD
, WriteFD
;
1018 if (std::error_code EC
= openFileForRead(From
, ReadFD
, OF_None
))
1020 if (std::error_code EC
=
1021 openFileForWrite(To
, WriteFD
, CD_CreateAlways
, OF_None
)) {
1026 std::error_code EC
= copy_file_internal(ReadFD
, WriteFD
);
1035 std::error_code
copy_file(const Twine
&From
, int ToFD
) {
1037 if (std::error_code EC
= openFileForRead(From
, ReadFD
, OF_None
))
1040 std::error_code EC
= copy_file_internal(ReadFD
, ToFD
);
1047 ErrorOr
<MD5::MD5Result
> md5_contents(int FD
) {
1050 constexpr size_t BufSize
= 4096;
1051 std::vector
<uint8_t> Buf(BufSize
);
1054 BytesRead
= read(FD
, Buf
.data(), BufSize
);
1057 Hash
.update(ArrayRef(Buf
.data(), BytesRead
));
1061 return errnoAsErrorCode();
1062 MD5::MD5Result Result
;
1067 ErrorOr
<MD5::MD5Result
> md5_contents(const Twine
&Path
) {
1069 if (auto EC
= openFileForRead(Path
, FD
, OF_None
))
1072 auto Result
= md5_contents(FD
);
1077 bool exists(const basic_file_status
&status
) {
1078 return status_known(status
) && status
.type() != file_type::file_not_found
;
1081 bool status_known(const basic_file_status
&s
) {
1082 return s
.type() != file_type::status_error
;
1085 file_type
get_file_type(const Twine
&Path
, bool Follow
) {
1087 if (status(Path
, st
, Follow
))
1088 return file_type::status_error
;
1092 bool is_directory(const basic_file_status
&status
) {
1093 return status
.type() == file_type::directory_file
;
1096 std::error_code
is_directory(const Twine
&path
, bool &result
) {
1098 if (std::error_code ec
= status(path
, st
))
1100 result
= is_directory(st
);
1101 return std::error_code();
1104 bool is_regular_file(const basic_file_status
&status
) {
1105 return status
.type() == file_type::regular_file
;
1108 std::error_code
is_regular_file(const Twine
&path
, bool &result
) {
1110 if (std::error_code ec
= status(path
, st
))
1112 result
= is_regular_file(st
);
1113 return std::error_code();
1116 bool is_symlink_file(const basic_file_status
&status
) {
1117 return status
.type() == file_type::symlink_file
;
1120 std::error_code
is_symlink_file(const Twine
&path
, bool &result
) {
1122 if (std::error_code ec
= status(path
, st
, false))
1124 result
= is_symlink_file(st
);
1125 return std::error_code();
1128 bool is_other(const basic_file_status
&status
) {
1129 return exists(status
) &&
1130 !is_regular_file(status
) &&
1131 !is_directory(status
);
1134 std::error_code
is_other(const Twine
&Path
, bool &Result
) {
1135 file_status FileStatus
;
1136 if (std::error_code EC
= status(Path
, FileStatus
))
1138 Result
= is_other(FileStatus
);
1139 return std::error_code();
1142 void directory_entry::replace_filename(const Twine
&Filename
, file_type Type
,
1143 basic_file_status Status
) {
1144 SmallString
<128> PathStr
= path::parent_path(Path
);
1145 path::append(PathStr
, Filename
);
1146 this->Path
= std::string(PathStr
);
1148 this->Status
= Status
;
1151 ErrorOr
<perms
> getPermissions(const Twine
&Path
) {
1153 if (std::error_code EC
= status(Path
, Status
))
1156 return Status
.permissions();
1159 size_t mapped_file_region::size() const {
1160 assert(Mapping
&& "Mapping failed but used anyway!");
1164 char *mapped_file_region::data() const {
1165 assert(Mapping
&& "Mapping failed but used anyway!");
1166 return reinterpret_cast<char *>(Mapping
);
1169 const char *mapped_file_region::const_data() const {
1170 assert(Mapping
&& "Mapping failed but used anyway!");
1171 return reinterpret_cast<const char *>(Mapping
);
1174 Error
readNativeFileToEOF(file_t FileHandle
, SmallVectorImpl
<char> &Buffer
,
1175 ssize_t ChunkSize
) {
1176 // Install a handler to truncate the buffer to the correct size on exit.
1177 size_t Size
= Buffer
.size();
1178 auto TruncateOnExit
= make_scope_exit([&]() { Buffer
.truncate(Size
); });
1180 // Read into Buffer until we hit EOF.
1182 Buffer
.resize_for_overwrite(Size
+ ChunkSize
);
1183 Expected
<size_t> ReadBytes
= readNativeFile(
1184 FileHandle
, MutableArrayRef(Buffer
.begin() + Size
, ChunkSize
));
1186 return ReadBytes
.takeError();
1187 if (*ReadBytes
== 0)
1188 return Error::success();
1193 } // end namespace fs
1194 } // end namespace sys
1195 } // end namespace llvm
1197 // Include the truly platform-specific parts.
1198 #if defined(LLVM_ON_UNIX)
1199 #include "Unix/Path.inc"
1202 #include "Windows/Path.inc"
1209 TempFile::TempFile(StringRef Name
, int FD
)
1210 : TmpName(std::string(Name
)), FD(FD
) {}
1211 TempFile::TempFile(TempFile
&&Other
) { *this = std::move(Other
); }
1212 TempFile
&TempFile::operator=(TempFile
&&Other
) {
1213 TmpName
= std::move(Other
.TmpName
);
1218 RemoveOnClose
= Other
.RemoveOnClose
;
1219 Other
.RemoveOnClose
= false;
1224 TempFile::~TempFile() { assert(Done
); }
1226 Error
TempFile::discard() {
1228 if (FD
!= -1 && close(FD
) == -1) {
1229 std::error_code EC
= errnoAsErrorCode();
1230 return errorCodeToError(EC
);
1235 // On Windows, closing will remove the file, if we set the delete
1236 // disposition. If not, remove it manually.
1237 bool Remove
= RemoveOnClose
;
1239 // Always try to remove the file.
1242 std::error_code RemoveEC
;
1243 if (Remove
&& !TmpName
.empty()) {
1244 RemoveEC
= fs::remove(TmpName
);
1245 sys::DontRemoveFileOnSignal(TmpName
);
1251 return errorCodeToError(RemoveEC
);
1254 Error
TempFile::keep(const Twine
&Name
) {
1257 // Always try to close and rename.
1259 // If we can't cancel the delete don't rename.
1260 auto H
= reinterpret_cast<HANDLE
>(_get_osfhandle(FD
));
1261 std::error_code RenameEC
=
1262 RemoveOnClose
? std::error_code() : setDeleteDisposition(H
, false);
1263 bool ShouldDelete
= false;
1265 RenameEC
= rename_handle(H
, Name
);
1266 // If rename failed because it's cross-device, copy instead
1268 std::error_code(ERROR_NOT_SAME_DEVICE
, std::system_category())) {
1269 RenameEC
= copy_file(TmpName
, Name
);
1270 ShouldDelete
= true;
1274 // If we can't rename or copy, discard the temporary file.
1276 ShouldDelete
= true;
1279 setDeleteDisposition(H
, true);
1284 std::error_code RenameEC
= fs::rename(TmpName
, Name
);
1286 // If we can't rename, try to copy to work around cross-device link issues.
1287 RenameEC
= sys::fs::copy_file(TmpName
, Name
);
1288 // If we can't rename or copy, discard the temporary file.
1293 sys::DontRemoveFileOnSignal(TmpName
);
1298 if (close(FD
) == -1)
1299 return errorCodeToError(errnoAsErrorCode());
1302 return errorCodeToError(RenameEC
);
1305 Error
TempFile::keep() {
1310 auto H
= reinterpret_cast<HANDLE
>(_get_osfhandle(FD
));
1311 if (std::error_code EC
= setDeleteDisposition(H
, false))
1312 return errorCodeToError(EC
);
1314 sys::DontRemoveFileOnSignal(TmpName
);
1318 if (close(FD
) == -1)
1319 return errorCodeToError(errnoAsErrorCode());
1322 return Error::success();
1325 Expected
<TempFile
> TempFile::create(const Twine
&Model
, unsigned Mode
,
1326 OpenFlags ExtraFlags
) {
1328 SmallString
<128> ResultPath
;
1329 if (std::error_code EC
=
1330 createUniqueFile(Model
, FD
, ResultPath
, OF_Delete
| ExtraFlags
, Mode
))
1331 return errorCodeToError(EC
);
1333 TempFile
Ret(ResultPath
, FD
);
1335 auto H
= reinterpret_cast<HANDLE
>(_get_osfhandle(FD
));
1336 bool SetSignalHandler
= false;
1337 if (std::error_code EC
= setDeleteDisposition(H
, true)) {
1338 Ret
.RemoveOnClose
= true;
1339 SetSignalHandler
= true;
1342 bool SetSignalHandler
= true;
1344 if (SetSignalHandler
&& sys::RemoveFileOnSignal(ResultPath
)) {
1345 // Make sure we delete the file when RemoveFileOnSignal fails.
1346 consumeError(Ret
.discard());
1347 std::error_code
EC(errc::operation_not_permitted
);
1348 return errorCodeToError(EC
);
1350 return std::move(Ret
);