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/Config/llvm-config.h"
16 #include "llvm/Support/Endian.h"
17 #include "llvm/Support/Errc.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Process.h"
21 #include "llvm/Support/Signals.h"
25 #if !defined(_MSC_VER) && !defined(__MINGW32__)
32 using namespace llvm::support::endian
;
35 using llvm::StringRef
;
36 using llvm::sys::path::is_separator
;
37 using llvm::sys::path::Style
;
39 inline Style
real_style(Style style
) {
41 return (style
== Style::posix
) ? Style::posix
: Style::windows
;
43 return (style
== Style::windows
) ? Style::windows
: Style::posix
;
47 inline const char *separators(Style style
) {
48 if (real_style(style
) == Style::windows
)
53 inline char preferred_separator(Style style
) {
54 if (real_style(style
) == Style::windows
)
59 StringRef
find_first_component(StringRef path
, Style style
) {
60 // Look for this first component in the following order.
61 // * empty (in this case we return an empty string)
62 // * either C: or {//,\\}net.
64 // * {file,directory}name
69 if (real_style(style
) == Style::windows
) {
71 if (path
.size() >= 2 &&
72 std::isalpha(static_cast<unsigned char>(path
[0])) && path
[1] == ':')
73 return path
.substr(0, 2);
77 if ((path
.size() > 2) && is_separator(path
[0], style
) &&
78 path
[0] == path
[1] && !is_separator(path
[2], style
)) {
79 // Find the next directory separator.
80 size_t end
= path
.find_first_of(separators(style
), 2);
81 return path
.substr(0, end
);
85 if (is_separator(path
[0], style
))
86 return path
.substr(0, 1);
88 // * {file,directory}name
89 size_t end
= path
.find_first_of(separators(style
));
90 return path
.substr(0, end
);
93 // Returns the first character of the filename in str. For paths ending in
94 // '/', it returns the position of the '/'.
95 size_t filename_pos(StringRef str
, Style style
) {
96 if (str
.size() > 0 && is_separator(str
[str
.size() - 1], style
))
97 return str
.size() - 1;
99 size_t pos
= str
.find_last_of(separators(style
), str
.size() - 1);
101 if (real_style(style
) == Style::windows
) {
102 if (pos
== StringRef::npos
)
103 pos
= str
.find_last_of(':', str
.size() - 2);
106 if (pos
== StringRef::npos
|| (pos
== 1 && is_separator(str
[0], style
)))
112 // Returns the position of the root directory in str. If there is no root
113 // directory in str, it returns StringRef::npos.
114 size_t root_dir_start(StringRef str
, Style style
) {
116 if (real_style(style
) == Style::windows
) {
117 if (str
.size() > 2 && str
[1] == ':' && is_separator(str
[2], style
))
122 if (str
.size() > 3 && is_separator(str
[0], style
) && str
[0] == str
[1] &&
123 !is_separator(str
[2], style
)) {
124 return str
.find_first_of(separators(style
), 2);
128 if (str
.size() > 0 && is_separator(str
[0], style
))
131 return StringRef::npos
;
134 // Returns the position past the end of the "parent path" of path. The parent
135 // path will not end in '/', unless the parent is the root directory. If the
136 // path has no parent, 0 is returned.
137 size_t parent_path_end(StringRef path
, Style style
) {
138 size_t end_pos
= filename_pos(path
, style
);
140 bool filename_was_sep
=
141 path
.size() > 0 && is_separator(path
[end_pos
], style
);
143 // Skip separators until we reach root dir (or the start of the string).
144 size_t root_dir_pos
= root_dir_start(path
, style
);
145 while (end_pos
> 0 &&
146 (root_dir_pos
== StringRef::npos
|| end_pos
> root_dir_pos
) &&
147 is_separator(path
[end_pos
- 1], style
))
150 if (end_pos
== root_dir_pos
&& !filename_was_sep
) {
151 // We've reached the root dir and the input path was *not* ending in a
152 // sequence of slashes. Include the root dir in the parent path.
153 return root_dir_pos
+ 1;
156 // Otherwise, just include before the last slash.
159 } // end unnamed namespace
167 static std::error_code
168 createUniqueEntity(const Twine
&Model
, int &ResultFD
,
169 SmallVectorImpl
<char> &ResultPath
, bool MakeAbsolute
,
170 unsigned Mode
, FSEntity Type
,
171 sys::fs::OpenFlags Flags
= sys::fs::OF_None
) {
172 SmallString
<128> ModelStorage
;
173 Model
.toVector(ModelStorage
);
176 // Make model absolute by prepending a temp directory if it's not already.
177 if (!sys::path::is_absolute(Twine(ModelStorage
))) {
178 SmallString
<128> TDir
;
179 sys::path::system_temp_directory(true, TDir
);
180 sys::path::append(TDir
, Twine(ModelStorage
));
181 ModelStorage
.swap(TDir
);
185 // From here on, DO NOT modify model. It may be needed if the randomly chosen
186 // path already exists.
187 ResultPath
= ModelStorage
;
189 ResultPath
.push_back(0);
190 ResultPath
.pop_back();
192 // Limit the number of attempts we make, so that we don't infinite loop. E.g.
193 // "permission denied" could be for a specific file (so we retry with a
194 // different name) or for the whole directory (retry would always fail).
195 // Checking which is racy, so we try a number of times, then give up.
197 for (int Retries
= 128; Retries
> 0; --Retries
) {
198 // Replace '%' with random chars.
199 for (unsigned i
= 0, e
= ModelStorage
.size(); i
!= e
; ++i
) {
200 if (ModelStorage
[i
] == '%')
202 "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
205 // Try to open + create the file.
208 EC
= sys::fs::openFileForReadWrite(Twine(ResultPath
.begin()), ResultFD
,
209 sys::fs::CD_CreateNew
, Flags
, Mode
);
211 // errc::permission_denied happens on Windows when we try to open a file
212 // that has been marked for deletion.
213 if (EC
== errc::file_exists
|| EC
== errc::permission_denied
)
218 return std::error_code();
222 EC
= sys::fs::access(ResultPath
.begin(), sys::fs::AccessMode::Exist
);
223 if (EC
== errc::no_such_file_or_directory
)
224 return std::error_code();
231 EC
= sys::fs::create_directory(ResultPath
.begin(), false);
233 if (EC
== errc::file_exists
)
237 return std::error_code();
240 llvm_unreachable("Invalid Type");
249 const_iterator
begin(StringRef path
, Style style
) {
252 i
.Component
= find_first_component(path
, style
);
258 const_iterator
end(StringRef path
) {
261 i
.Position
= path
.size();
265 const_iterator
&const_iterator::operator++() {
266 assert(Position
< Path
.size() && "Tried to increment past end!");
268 // Increment Position to past the current component
269 Position
+= Component
.size();
272 if (Position
== Path
.size()) {
273 Component
= StringRef();
277 // Both POSIX and Windows treat paths that begin with exactly two separators
279 bool was_net
= Component
.size() > 2 && is_separator(Component
[0], S
) &&
280 Component
[1] == Component
[0] && !is_separator(Component
[2], S
);
282 // Handle separators.
283 if (is_separator(Path
[Position
], S
)) {
287 (real_style(S
) == Style::windows
&& Component
.endswith(":"))) {
288 Component
= Path
.substr(Position
, 1);
292 // Skip extra separators.
293 while (Position
!= Path
.size() && is_separator(Path
[Position
], S
)) {
297 // Treat trailing '/' as a '.', unless it is the root dir.
298 if (Position
== Path
.size() && Component
!= "/") {
305 // Find next component.
306 size_t end_pos
= Path
.find_first_of(separators(S
), Position
);
307 Component
= Path
.slice(Position
, end_pos
);
312 bool const_iterator::operator==(const const_iterator
&RHS
) const {
313 return Path
.begin() == RHS
.Path
.begin() && Position
== RHS
.Position
;
316 ptrdiff_t const_iterator::operator-(const const_iterator
&RHS
) const {
317 return Position
- RHS
.Position
;
320 reverse_iterator
rbegin(StringRef Path
, Style style
) {
323 I
.Position
= Path
.size();
328 reverse_iterator
rend(StringRef Path
) {
331 I
.Component
= Path
.substr(0, 0);
336 reverse_iterator
&reverse_iterator::operator++() {
337 size_t root_dir_pos
= root_dir_start(Path
, S
);
339 // Skip separators unless it's the root directory.
340 size_t end_pos
= Position
;
341 while (end_pos
> 0 && (end_pos
- 1) != root_dir_pos
&&
342 is_separator(Path
[end_pos
- 1], S
))
345 // Treat trailing '/' as a '.', unless it is the root dir.
346 if (Position
== Path
.size() && !Path
.empty() &&
347 is_separator(Path
.back(), S
) &&
348 (root_dir_pos
== StringRef::npos
|| end_pos
- 1 > root_dir_pos
)) {
354 // Find next separator.
355 size_t start_pos
= filename_pos(Path
.substr(0, end_pos
), S
);
356 Component
= Path
.slice(start_pos
, end_pos
);
357 Position
= start_pos
;
361 bool reverse_iterator::operator==(const reverse_iterator
&RHS
) const {
362 return Path
.begin() == RHS
.Path
.begin() && Component
== RHS
.Component
&&
363 Position
== RHS
.Position
;
366 ptrdiff_t reverse_iterator::operator-(const reverse_iterator
&RHS
) const {
367 return Position
- RHS
.Position
;
370 StringRef
root_path(StringRef path
, Style style
) {
371 const_iterator b
= begin(path
, style
), pos
= b
, e
= end(path
);
374 b
->size() > 2 && is_separator((*b
)[0], style
) && (*b
)[1] == (*b
)[0];
375 bool has_drive
= (real_style(style
) == Style::windows
) && b
->endswith(":");
377 if (has_net
|| has_drive
) {
378 if ((++pos
!= e
) && is_separator((*pos
)[0], style
)) {
379 // {C:/,//net/}, so get the first two components.
380 return path
.substr(0, b
->size() + pos
->size());
382 // just {C:,//net}, return the first component.
387 // POSIX style root directory.
388 if (is_separator((*b
)[0], style
)) {
396 StringRef
root_name(StringRef path
, Style style
) {
397 const_iterator b
= begin(path
, style
), e
= end(path
);
400 b
->size() > 2 && is_separator((*b
)[0], style
) && (*b
)[1] == (*b
)[0];
401 bool has_drive
= (real_style(style
) == Style::windows
) && b
->endswith(":");
403 if (has_net
|| has_drive
) {
404 // just {C:,//net}, return the first component.
409 // No path or no name.
413 StringRef
root_directory(StringRef path
, Style style
) {
414 const_iterator b
= begin(path
, style
), pos
= b
, e
= end(path
);
417 b
->size() > 2 && is_separator((*b
)[0], style
) && (*b
)[1] == (*b
)[0];
418 bool has_drive
= (real_style(style
) == Style::windows
) && b
->endswith(":");
420 if ((has_net
|| has_drive
) &&
421 // {C:,//net}, skip to the next component.
422 (++pos
!= e
) && is_separator((*pos
)[0], style
)) {
426 // POSIX style root directory.
427 if (!has_net
&& is_separator((*b
)[0], style
)) {
432 // No path or no root.
436 StringRef
relative_path(StringRef path
, Style style
) {
437 StringRef root
= root_path(path
, style
);
438 return path
.substr(root
.size());
441 void append(SmallVectorImpl
<char> &path
, Style style
, const Twine
&a
,
442 const Twine
&b
, const Twine
&c
, const Twine
&d
) {
443 SmallString
<32> a_storage
;
444 SmallString
<32> b_storage
;
445 SmallString
<32> c_storage
;
446 SmallString
<32> d_storage
;
448 SmallVector
<StringRef
, 4> components
;
449 if (!a
.isTriviallyEmpty()) components
.push_back(a
.toStringRef(a_storage
));
450 if (!b
.isTriviallyEmpty()) components
.push_back(b
.toStringRef(b_storage
));
451 if (!c
.isTriviallyEmpty()) components
.push_back(c
.toStringRef(c_storage
));
452 if (!d
.isTriviallyEmpty()) components
.push_back(d
.toStringRef(d_storage
));
454 for (auto &component
: components
) {
456 !path
.empty() && is_separator(path
[path
.size() - 1], style
);
458 // Strip separators from beginning of component.
459 size_t loc
= component
.find_first_not_of(separators(style
));
460 StringRef c
= component
.substr(loc
);
463 path
.append(c
.begin(), c
.end());
467 bool component_has_sep
=
468 !component
.empty() && is_separator(component
[0], style
);
469 if (!component_has_sep
&&
470 !(path
.empty() || has_root_name(component
, style
))) {
472 path
.push_back(preferred_separator(style
));
475 path
.append(component
.begin(), component
.end());
479 void append(SmallVectorImpl
<char> &path
, const Twine
&a
, const Twine
&b
,
480 const Twine
&c
, const Twine
&d
) {
481 append(path
, Style::native
, a
, b
, c
, d
);
484 void append(SmallVectorImpl
<char> &path
, const_iterator begin
,
485 const_iterator end
, Style style
) {
486 for (; begin
!= end
; ++begin
)
487 path::append(path
, style
, *begin
);
490 StringRef
parent_path(StringRef path
, Style style
) {
491 size_t end_pos
= parent_path_end(path
, style
);
492 if (end_pos
== StringRef::npos
)
495 return path
.substr(0, end_pos
);
498 void remove_filename(SmallVectorImpl
<char> &path
, Style style
) {
499 size_t end_pos
= parent_path_end(StringRef(path
.begin(), path
.size()), style
);
500 if (end_pos
!= StringRef::npos
)
501 path
.set_size(end_pos
);
504 void replace_extension(SmallVectorImpl
<char> &path
, const Twine
&extension
,
506 StringRef
p(path
.begin(), path
.size());
507 SmallString
<32> ext_storage
;
508 StringRef ext
= extension
.toStringRef(ext_storage
);
510 // Erase existing extension.
511 size_t pos
= p
.find_last_of('.');
512 if (pos
!= StringRef::npos
&& pos
>= filename_pos(p
, style
))
515 // Append '.' if needed.
516 if (ext
.size() > 0 && ext
[0] != '.')
520 path
.append(ext
.begin(), ext
.end());
523 void replace_path_prefix(SmallVectorImpl
<char> &Path
,
524 const StringRef
&OldPrefix
, const StringRef
&NewPrefix
,
526 if (OldPrefix
.empty() && NewPrefix
.empty())
529 StringRef
OrigPath(Path
.begin(), Path
.size());
530 if (!OrigPath
.startswith(OldPrefix
))
533 // If prefixes have the same size we can simply copy the new one over.
534 if (OldPrefix
.size() == NewPrefix
.size()) {
535 llvm::copy(NewPrefix
, Path
.begin());
539 StringRef RelPath
= OrigPath
.substr(OldPrefix
.size());
540 SmallString
<256> NewPath
;
541 path::append(NewPath
, style
, NewPrefix
);
542 path::append(NewPath
, style
, RelPath
);
546 void native(const Twine
&path
, SmallVectorImpl
<char> &result
, Style style
) {
547 assert((!path
.isSingleStringRef() ||
548 path
.getSingleStringRef().data() != result
.data()) &&
549 "path and result are not allowed to overlap!");
552 path
.toVector(result
);
553 native(result
, style
);
556 void native(SmallVectorImpl
<char> &Path
, Style style
) {
559 if (real_style(style
) == Style::windows
) {
560 std::replace(Path
.begin(), Path
.end(), '/', '\\');
561 if (Path
[0] == '~' && (Path
.size() == 1 || is_separator(Path
[1], style
))) {
562 SmallString
<128> PathHome
;
563 home_directory(PathHome
);
564 PathHome
.append(Path
.begin() + 1, Path
.end());
568 for (auto PI
= Path
.begin(), PE
= Path
.end(); PI
< PE
; ++PI
) {
571 if (PN
< PE
&& *PN
== '\\')
572 ++PI
; // increment once, the for loop will move over the escaped slash
580 std::string
convert_to_slash(StringRef path
, Style style
) {
581 if (real_style(style
) != Style::windows
)
584 std::string s
= path
.str();
585 std::replace(s
.begin(), s
.end(), '\\', '/');
589 StringRef
filename(StringRef path
, Style style
) { return *rbegin(path
, style
); }
591 StringRef
stem(StringRef path
, Style style
) {
592 StringRef fname
= filename(path
, style
);
593 size_t pos
= fname
.find_last_of('.');
594 if (pos
== StringRef::npos
)
597 if ((fname
.size() == 1 && fname
== ".") ||
598 (fname
.size() == 2 && fname
== ".."))
601 return fname
.substr(0, pos
);
604 StringRef
extension(StringRef path
, Style style
) {
605 StringRef fname
= filename(path
, style
);
606 size_t pos
= fname
.find_last_of('.');
607 if (pos
== StringRef::npos
)
610 if ((fname
.size() == 1 && fname
== ".") ||
611 (fname
.size() == 2 && fname
== ".."))
614 return fname
.substr(pos
);
617 bool is_separator(char value
, Style style
) {
620 if (real_style(style
) == Style::windows
)
621 return value
== '\\';
625 StringRef
get_separator(Style style
) {
626 if (real_style(style
) == Style::windows
)
631 bool has_root_name(const Twine
&path
, Style style
) {
632 SmallString
<128> path_storage
;
633 StringRef p
= path
.toStringRef(path_storage
);
635 return !root_name(p
, style
).empty();
638 bool has_root_directory(const Twine
&path
, Style style
) {
639 SmallString
<128> path_storage
;
640 StringRef p
= path
.toStringRef(path_storage
);
642 return !root_directory(p
, style
).empty();
645 bool has_root_path(const Twine
&path
, Style style
) {
646 SmallString
<128> path_storage
;
647 StringRef p
= path
.toStringRef(path_storage
);
649 return !root_path(p
, style
).empty();
652 bool has_relative_path(const Twine
&path
, Style style
) {
653 SmallString
<128> path_storage
;
654 StringRef p
= path
.toStringRef(path_storage
);
656 return !relative_path(p
, style
).empty();
659 bool has_filename(const Twine
&path
, Style style
) {
660 SmallString
<128> path_storage
;
661 StringRef p
= path
.toStringRef(path_storage
);
663 return !filename(p
, style
).empty();
666 bool has_parent_path(const Twine
&path
, Style style
) {
667 SmallString
<128> path_storage
;
668 StringRef p
= path
.toStringRef(path_storage
);
670 return !parent_path(p
, style
).empty();
673 bool has_stem(const Twine
&path
, Style style
) {
674 SmallString
<128> path_storage
;
675 StringRef p
= path
.toStringRef(path_storage
);
677 return !stem(p
, style
).empty();
680 bool has_extension(const Twine
&path
, Style style
) {
681 SmallString
<128> path_storage
;
682 StringRef p
= path
.toStringRef(path_storage
);
684 return !extension(p
, style
).empty();
687 bool is_absolute(const Twine
&path
, Style style
) {
688 SmallString
<128> path_storage
;
689 StringRef p
= path
.toStringRef(path_storage
);
691 bool rootDir
= has_root_directory(p
, style
);
693 (real_style(style
) != Style::windows
) || has_root_name(p
, style
);
695 return rootDir
&& rootName
;
698 bool is_relative(const Twine
&path
, Style style
) {
699 return !is_absolute(path
, style
);
702 StringRef
remove_leading_dotslash(StringRef Path
, Style style
) {
703 // Remove leading "./" (or ".//" or "././" etc.)
704 while (Path
.size() > 2 && Path
[0] == '.' && is_separator(Path
[1], style
)) {
705 Path
= Path
.substr(2);
706 while (Path
.size() > 0 && is_separator(Path
[0], style
))
707 Path
= Path
.substr(1);
712 static SmallString
<256> remove_dots(StringRef path
, bool remove_dot_dot
,
714 SmallVector
<StringRef
, 16> components
;
716 // Skip the root path, then look for traversal in the components.
717 StringRef rel
= path::relative_path(path
, style
);
719 llvm::make_range(path::begin(rel
, style
), path::end(rel
))) {
722 // Leading ".." will remain in the path unless it's at the root.
723 if (remove_dot_dot
&& C
== "..") {
724 if (!components
.empty() && components
.back() != "..") {
725 components
.pop_back();
728 if (path::is_absolute(path
, style
))
731 components
.push_back(C
);
734 SmallString
<256> buffer
= path::root_path(path
, style
);
735 for (StringRef C
: components
)
736 path::append(buffer
, style
, C
);
740 bool remove_dots(SmallVectorImpl
<char> &path
, bool remove_dot_dot
,
742 StringRef
p(path
.data(), path
.size());
744 SmallString
<256> result
= remove_dots(p
, remove_dot_dot
, style
);
752 } // end namespace path
756 std::error_code
getUniqueID(const Twine Path
, UniqueID
&Result
) {
758 std::error_code EC
= status(Path
, Status
);
761 Result
= Status
.getUniqueID();
762 return std::error_code();
765 std::error_code
createUniqueFile(const Twine
&Model
, int &ResultFd
,
766 SmallVectorImpl
<char> &ResultPath
,
768 return createUniqueEntity(Model
, ResultFd
, ResultPath
, false, Mode
, FS_File
);
771 static std::error_code
createUniqueFile(const Twine
&Model
, int &ResultFd
,
772 SmallVectorImpl
<char> &ResultPath
,
773 unsigned Mode
, OpenFlags Flags
) {
774 return createUniqueEntity(Model
, ResultFd
, ResultPath
, false, Mode
, FS_File
,
778 std::error_code
createUniqueFile(const Twine
&Model
,
779 SmallVectorImpl
<char> &ResultPath
,
782 auto EC
= createUniqueFile(Model
, FD
, ResultPath
, Mode
);
785 // FD is only needed to avoid race conditions. Close it right away.
790 static std::error_code
791 createTemporaryFile(const Twine
&Model
, int &ResultFD
,
792 llvm::SmallVectorImpl
<char> &ResultPath
, FSEntity Type
) {
793 SmallString
<128> Storage
;
794 StringRef P
= Model
.toNullTerminatedStringRef(Storage
);
795 assert(P
.find_first_of(separators(Style::native
)) == StringRef::npos
&&
796 "Model must be a simple filename.");
797 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
798 return createUniqueEntity(P
.begin(), ResultFD
, ResultPath
, true,
799 owner_read
| owner_write
, Type
);
802 static std::error_code
803 createTemporaryFile(const Twine
&Prefix
, StringRef Suffix
, int &ResultFD
,
804 llvm::SmallVectorImpl
<char> &ResultPath
, FSEntity Type
) {
805 const char *Middle
= Suffix
.empty() ? "-%%%%%%" : "-%%%%%%.";
806 return createTemporaryFile(Prefix
+ Middle
+ Suffix
, ResultFD
, ResultPath
,
810 std::error_code
createTemporaryFile(const Twine
&Prefix
, StringRef Suffix
,
812 SmallVectorImpl
<char> &ResultPath
) {
813 return createTemporaryFile(Prefix
, Suffix
, ResultFD
, ResultPath
, FS_File
);
816 std::error_code
createTemporaryFile(const Twine
&Prefix
, StringRef Suffix
,
817 SmallVectorImpl
<char> &ResultPath
) {
819 auto EC
= createTemporaryFile(Prefix
, Suffix
, FD
, ResultPath
);
822 // FD is only needed to avoid race conditions. Close it right away.
828 // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
829 // for consistency. We should try using mkdtemp.
830 std::error_code
createUniqueDirectory(const Twine
&Prefix
,
831 SmallVectorImpl
<char> &ResultPath
) {
833 return createUniqueEntity(Prefix
+ "-%%%%%%", Dummy
, ResultPath
, true, 0,
838 getPotentiallyUniqueFileName(const Twine
&Model
,
839 SmallVectorImpl
<char> &ResultPath
) {
841 return createUniqueEntity(Model
, Dummy
, ResultPath
, false, 0, FS_Name
);
845 getPotentiallyUniqueTempFileName(const Twine
&Prefix
, StringRef Suffix
,
846 SmallVectorImpl
<char> &ResultPath
) {
848 return createTemporaryFile(Prefix
, Suffix
, Dummy
, ResultPath
, FS_Name
);
851 void make_absolute(const Twine
¤t_directory
,
852 SmallVectorImpl
<char> &path
) {
853 StringRef
p(path
.data(), path
.size());
855 bool rootDirectory
= path::has_root_directory(p
);
857 (real_style(Style::native
) != Style::windows
) || path::has_root_name(p
);
860 if (rootName
&& rootDirectory
)
863 // All of the following conditions will need the current directory.
864 SmallString
<128> current_dir
;
865 current_directory
.toVector(current_dir
);
867 // Relative path. Prepend the current directory.
868 if (!rootName
&& !rootDirectory
) {
869 // Append path to the current directory.
870 path::append(current_dir
, p
);
871 // Set path to the result.
872 path
.swap(current_dir
);
876 if (!rootName
&& rootDirectory
) {
877 StringRef cdrn
= path::root_name(current_dir
);
878 SmallString
<128> curDirRootName(cdrn
.begin(), cdrn
.end());
879 path::append(curDirRootName
, p
);
880 // Set path to the result.
881 path
.swap(curDirRootName
);
885 if (rootName
&& !rootDirectory
) {
886 StringRef pRootName
= path::root_name(p
);
887 StringRef bRootDirectory
= path::root_directory(current_dir
);
888 StringRef bRelativePath
= path::relative_path(current_dir
);
889 StringRef pRelativePath
= path::relative_path(p
);
891 SmallString
<128> res
;
892 path::append(res
, pRootName
, bRootDirectory
, bRelativePath
, pRelativePath
);
897 llvm_unreachable("All rootName and rootDirectory combinations should have "
901 std::error_code
make_absolute(SmallVectorImpl
<char> &path
) {
902 if (path::is_absolute(path
))
905 SmallString
<128> current_dir
;
906 if (std::error_code ec
= current_path(current_dir
))
909 make_absolute(current_dir
, path
);
913 std::error_code
create_directories(const Twine
&Path
, bool IgnoreExisting
,
915 SmallString
<128> PathStorage
;
916 StringRef P
= Path
.toStringRef(PathStorage
);
918 // Be optimistic and try to create the directory
919 std::error_code EC
= create_directory(P
, IgnoreExisting
, Perms
);
920 // If we succeeded, or had any error other than the parent not existing, just
922 if (EC
!= errc::no_such_file_or_directory
)
925 // We failed because of a no_such_file_or_directory, try to create the
927 StringRef Parent
= path::parent_path(P
);
931 if ((EC
= create_directories(Parent
, IgnoreExisting
, Perms
)))
934 return create_directory(P
, IgnoreExisting
, Perms
);
937 static std::error_code
copy_file_internal(int ReadFD
, int WriteFD
) {
938 const size_t BufSize
= 4096;
939 char *Buf
= new char[BufSize
];
940 int BytesRead
= 0, BytesWritten
= 0;
942 BytesRead
= read(ReadFD
, Buf
, BufSize
);
946 BytesWritten
= write(WriteFD
, Buf
, BytesRead
);
947 if (BytesWritten
< 0)
949 BytesRead
-= BytesWritten
;
951 if (BytesWritten
< 0)
956 if (BytesRead
< 0 || BytesWritten
< 0)
957 return std::error_code(errno
, std::generic_category());
958 return std::error_code();
961 std::error_code
copy_file(const Twine
&From
, const Twine
&To
) {
963 if (std::error_code EC
= openFileForRead(From
, ReadFD
, OF_None
))
965 if (std::error_code EC
=
966 openFileForWrite(To
, WriteFD
, CD_CreateAlways
, OF_None
)) {
971 std::error_code EC
= copy_file_internal(ReadFD
, WriteFD
);
979 std::error_code
copy_file(const Twine
&From
, int ToFD
) {
981 if (std::error_code EC
= openFileForRead(From
, ReadFD
, OF_None
))
984 std::error_code EC
= copy_file_internal(ReadFD
, ToFD
);
991 ErrorOr
<MD5::MD5Result
> md5_contents(int FD
) {
994 constexpr size_t BufSize
= 4096;
995 std::vector
<uint8_t> Buf(BufSize
);
998 BytesRead
= read(FD
, Buf
.data(), BufSize
);
1001 Hash
.update(makeArrayRef(Buf
.data(), BytesRead
));
1005 return std::error_code(errno
, std::generic_category());
1006 MD5::MD5Result Result
;
1011 ErrorOr
<MD5::MD5Result
> md5_contents(const Twine
&Path
) {
1013 if (auto EC
= openFileForRead(Path
, FD
, OF_None
))
1016 auto Result
= md5_contents(FD
);
1021 bool exists(const basic_file_status
&status
) {
1022 return status_known(status
) && status
.type() != file_type::file_not_found
;
1025 bool status_known(const basic_file_status
&s
) {
1026 return s
.type() != file_type::status_error
;
1029 file_type
get_file_type(const Twine
&Path
, bool Follow
) {
1031 if (status(Path
, st
, Follow
))
1032 return file_type::status_error
;
1036 bool is_directory(const basic_file_status
&status
) {
1037 return status
.type() == file_type::directory_file
;
1040 std::error_code
is_directory(const Twine
&path
, bool &result
) {
1042 if (std::error_code ec
= status(path
, st
))
1044 result
= is_directory(st
);
1045 return std::error_code();
1048 bool is_regular_file(const basic_file_status
&status
) {
1049 return status
.type() == file_type::regular_file
;
1052 std::error_code
is_regular_file(const Twine
&path
, bool &result
) {
1054 if (std::error_code ec
= status(path
, st
))
1056 result
= is_regular_file(st
);
1057 return std::error_code();
1060 bool is_symlink_file(const basic_file_status
&status
) {
1061 return status
.type() == file_type::symlink_file
;
1064 std::error_code
is_symlink_file(const Twine
&path
, bool &result
) {
1066 if (std::error_code ec
= status(path
, st
, false))
1068 result
= is_symlink_file(st
);
1069 return std::error_code();
1072 bool is_other(const basic_file_status
&status
) {
1073 return exists(status
) &&
1074 !is_regular_file(status
) &&
1075 !is_directory(status
);
1078 std::error_code
is_other(const Twine
&Path
, bool &Result
) {
1079 file_status FileStatus
;
1080 if (std::error_code EC
= status(Path
, FileStatus
))
1082 Result
= is_other(FileStatus
);
1083 return std::error_code();
1086 void directory_entry::replace_filename(const Twine
&Filename
, file_type Type
,
1087 basic_file_status Status
) {
1088 SmallString
<128> PathStr
= path::parent_path(Path
);
1089 path::append(PathStr
, Filename
);
1090 this->Path
= PathStr
.str();
1092 this->Status
= Status
;
1095 ErrorOr
<perms
> getPermissions(const Twine
&Path
) {
1097 if (std::error_code EC
= status(Path
, Status
))
1100 return Status
.permissions();
1103 } // end namespace fs
1104 } // end namespace sys
1105 } // end namespace llvm
1107 // Include the truly platform-specific parts.
1108 #if defined(LLVM_ON_UNIX)
1109 #include "Unix/Path.inc"
1112 #include "Windows/Path.inc"
1118 TempFile::TempFile(StringRef Name
, int FD
) : TmpName(Name
), FD(FD
) {}
1119 TempFile::TempFile(TempFile
&&Other
) { *this = std::move(Other
); }
1120 TempFile
&TempFile::operator=(TempFile
&&Other
) {
1121 TmpName
= std::move(Other
.TmpName
);
1127 TempFile::~TempFile() { assert(Done
); }
1129 Error
TempFile::discard() {
1131 if (FD
!= -1 && close(FD
) == -1) {
1132 std::error_code EC
= std::error_code(errno
, std::generic_category());
1133 return errorCodeToError(EC
);
1138 // On windows closing will remove the file.
1140 return Error::success();
1142 // Always try to close and remove.
1143 std::error_code RemoveEC
;
1144 if (!TmpName
.empty()) {
1145 RemoveEC
= fs::remove(TmpName
);
1146 sys::DontRemoveFileOnSignal(TmpName
);
1150 return errorCodeToError(RemoveEC
);
1154 Error
TempFile::keep(const Twine
&Name
) {
1157 // Always try to close and rename.
1159 // If we can't cancel the delete don't rename.
1160 auto H
= reinterpret_cast<HANDLE
>(_get_osfhandle(FD
));
1161 std::error_code RenameEC
= setDeleteDisposition(H
, false);
1163 RenameEC
= rename_fd(FD
, Name
);
1164 // If rename failed because it's cross-device, copy instead
1166 std::error_code(ERROR_NOT_SAME_DEVICE
, std::system_category())) {
1167 RenameEC
= copy_file(TmpName
, Name
);
1168 setDeleteDisposition(H
, true);
1172 // If we can't rename, discard the temporary file.
1174 setDeleteDisposition(H
, true);
1176 std::error_code RenameEC
= fs::rename(TmpName
, Name
);
1178 // If we can't rename, try to copy to work around cross-device link issues.
1179 RenameEC
= sys::fs::copy_file(TmpName
, Name
);
1180 // If we can't rename or copy, discard the temporary file.
1184 sys::DontRemoveFileOnSignal(TmpName
);
1190 if (close(FD
) == -1) {
1191 std::error_code
EC(errno
, std::generic_category());
1192 return errorCodeToError(EC
);
1196 return errorCodeToError(RenameEC
);
1199 Error
TempFile::keep() {
1204 auto H
= reinterpret_cast<HANDLE
>(_get_osfhandle(FD
));
1205 if (std::error_code EC
= setDeleteDisposition(H
, false))
1206 return errorCodeToError(EC
);
1208 sys::DontRemoveFileOnSignal(TmpName
);
1213 if (close(FD
) == -1) {
1214 std::error_code
EC(errno
, std::generic_category());
1215 return errorCodeToError(EC
);
1219 return Error::success();
1222 Expected
<TempFile
> TempFile::create(const Twine
&Model
, unsigned Mode
) {
1224 SmallString
<128> ResultPath
;
1225 if (std::error_code EC
=
1226 createUniqueFile(Model
, FD
, ResultPath
, Mode
, OF_Delete
))
1227 return errorCodeToError(EC
);
1229 TempFile
Ret(ResultPath
, FD
);
1231 if (sys::RemoveFileOnSignal(ResultPath
)) {
1232 // Make sure we delete the file when RemoveFileOnSignal fails.
1233 consumeError(Ret
.discard());
1234 std::error_code
EC(errc::operation_not_permitted
);
1235 return errorCodeToError(EC
);
1238 return std::move(Ret
);
1242 } // end namsspace sys
1243 } // end namespace llvm