LLVM 23.0.0git
Path.cpp
Go to the documentation of this file.
1//===-- Path.cpp - Implement OS Path Concept ------------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the operating system Path API.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Support/Path.h"
14#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/ScopeExit.h"
17#include "llvm/Config/config.h"
18#include "llvm/Config/llvm-config.h"
19#include "llvm/Support/Errc.h"
25#include <cctype>
26
27#if !defined(_MSC_VER) && !defined(__MINGW32__)
28#include <unistd.h>
29#else
30#include <io.h>
31#endif
32
33using namespace llvm;
34using namespace llvm::support::endian;
35
36namespace {
37 using llvm::StringRef;
40
41 inline Style real_style(Style style) {
42 if (style != Style::native)
43 return style;
44 if (is_style_posix(style))
45 return Style::posix;
46 return LLVM_WINDOWS_PREFER_FORWARD_SLASH ? Style::windows_slash
47 : Style::windows_backslash;
48 }
49
50 inline const char *separators(Style style) {
51 if (is_style_windows(style))
52 return "\\/";
53 return "/";
54 }
55
56 inline char preferred_separator(Style style) {
57 if (real_style(style) == Style::windows)
58 return '\\';
59 return '/';
60 }
61
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.
66 // * {/,\}
67 // * {file,directory}name
68
69 if (path.empty())
70 return path;
71
72 if (is_style_windows(style)) {
73 // C:
74 if (path.size() >= 2 &&
75 std::isalpha(static_cast<unsigned char>(path[0])) && path[1] == ':')
76 return path.substr(0, 2);
77 }
78
79 // //net
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);
85 }
86
87 // {/,\}
88 if (is_separator(path[0], style))
89 return path.substr(0, 1);
90
91 // * {file,directory}name
92 size_t end = path.find_first_of(separators(style));
93 return path.substr(0, end);
94 }
95
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;
101
102 size_t pos = str.find_last_of(separators(style), str.size() - 1);
103
104 if (is_style_windows(style)) {
105 if (pos == StringRef::npos)
106 pos = str.find_last_of(':', str.size() - 1);
107 }
108
109 if (pos == StringRef::npos || (pos == 1 && is_separator(str[0], style)))
110 return 0;
111
112 return pos + 1;
113 }
114
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) {
118 // case "c:/"
119 if (is_style_windows(style)) {
120 if (str.size() > 2 && str[1] == ':' && is_separator(str[2], style))
121 return 2;
122 }
123
124 // case "//net"
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);
128 }
129
130 // case "/"
131 if (str.size() > 0 && is_separator(str[0], style))
132 return 0;
133
134 return StringRef::npos;
135 }
136
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);
142
143 bool filename_was_sep =
144 path.size() > 0 && is_separator(path[end_pos], style);
145
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))
151 --end_pos;
152
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;
157 }
158
159 // Otherwise, just include before the last slash.
160 return end_pos;
161 }
162} // end unnamed namespace
163
169
170static std::error_code
171createUniqueEntity(const Twine &Model, int &ResultFD,
172 SmallVectorImpl<char> &ResultPath, bool MakeAbsolute,
174 unsigned Mode = 0) {
175
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.
180 std::error_code EC;
181 for (int Retries = 128; Retries > 0; --Retries) {
182 sys::fs::createUniquePath(Model, ResultPath, MakeAbsolute);
183 // Try to open + create the file.
184 switch (Type) {
185 case FS_File: {
186 EC = sys::fs::openFileForReadWrite(Twine(ResultPath.begin()), ResultFD,
188 if (EC) {
189 // errc::permission_denied happens on Windows when we try to open a file
190 // that has been marked for deletion.
192 continue;
193 return EC;
194 }
195
196 return std::error_code();
197 }
198
199 case FS_Name: {
202 return std::error_code();
203 if (EC)
204 return EC;
205 continue;
206 }
207
208 case FS_Dir: {
209 EC = sys::fs::create_directory(ResultPath.begin(), false);
210 if (EC) {
211 if (EC == errc::file_exists)
212 continue;
213 return EC;
214 }
215 return std::error_code();
216 }
217 }
218 llvm_unreachable("Invalid Type");
219 }
220 return EC;
221}
222
223namespace llvm {
224namespace sys {
225namespace path {
226
229 i.Path = path;
230 i.Component = find_first_component(path, style);
231 i.Position = 0;
232 i.S = style;
233 return i;
234}
235
238 i.Path = path;
239 i.Position = path.size();
240 return i;
241}
242
244 assert(Position < Path.size() && "Tried to increment past end!");
245
246 // Increment Position to past the current component
247 Position += Component.size();
248
249 // Check for end.
250 if (Position == Path.size()) {
251 Component = StringRef();
252 return *this;
253 }
254
255 // Both POSIX and Windows treat paths that begin with exactly two separators
256 // specially.
257 bool was_net = Component.size() > 2 && is_separator(Component[0], S) &&
258 Component[1] == Component[0] && !is_separator(Component[2], S);
259
260 // Handle separators.
261 if (is_separator(Path[Position], S)) {
262 // Root dir.
263 if (was_net ||
264 // c:/
265 (is_style_windows(S) && Component.ends_with(":"))) {
266 Component = Path.substr(Position, 1);
267 return *this;
268 }
269
270 // Skip extra separators.
271 while (Position != Path.size() && is_separator(Path[Position], S)) {
272 ++Position;
273 }
274
275 // Treat trailing '/' as a '.', unless it is the root dir.
276 if (Position == Path.size() && Component != "/") {
277 --Position;
278 Component = ".";
279 return *this;
280 }
281 }
282
283 // Find next component.
284 size_t end_pos = Path.find_first_of(separators(S), Position);
285 Component = Path.slice(Position, end_pos);
286
287 return *this;
288}
289
291 return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
292}
293
295 return Position - RHS.Position;
296}
297
300 I.Path = Path;
301 I.Position = Path.size();
302 I.S = style;
303 ++I;
304 return I;
305}
306
309 I.Path = Path;
310 I.Component = Path.substr(0, 0);
311 I.Position = 0;
312 return I;
313}
314
316 size_t root_dir_pos = root_dir_start(Path, S);
317
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))
322 --end_pos;
323
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)) {
328 --Position;
329 Component = ".";
330 return *this;
331 }
332
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;
337 return *this;
338}
339
341 return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
342 Position == RHS.Position;
343}
344
346 return Position - RHS.Position;
347}
348
350 const_iterator b = begin(path, style), pos = b, e = end(path);
351 if (b != e) {
352 bool has_net =
353 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
354 bool has_drive = is_style_windows(style) && b->ends_with(":");
355
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());
360 }
361 // just {C:,//net}, return the first component.
362 return *b;
363 }
364
365 // POSIX style root directory.
366 if (is_separator((*b)[0], style)) {
367 return *b;
368 }
369 }
370
371 return StringRef();
372}
373
375 const_iterator b = begin(path, style), e = end(path);
376 if (b != e) {
377 bool has_net =
378 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
379 bool has_drive = is_style_windows(style) && b->ends_with(":");
380
381 if (has_net || has_drive) {
382 // just {C:,//net}, return the first component.
383 return *b;
384 }
385 }
386
387 // No path or no name.
388 return StringRef();
389}
390
392 const_iterator b = begin(path, style), pos = b, e = end(path);
393 if (b != e) {
394 bool has_net =
395 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
396 bool has_drive = is_style_windows(style) && b->ends_with(":");
397
398 if ((has_net || has_drive) &&
399 // {C:,//net}, skip to the next component.
400 (++pos != e) && is_separator((*pos)[0], style)) {
401 return *pos;
402 }
403
404 // POSIX style root directory.
405 if (!has_net && is_separator((*b)[0], style)) {
406 return *b;
407 }
408 }
409
410 // No path or no root.
411 return StringRef();
412}
413
415 StringRef root = root_path(path, style);
416 return path.substr(root.size());
417}
418
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;
425
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));
431
432 for (auto &component : components) {
433 bool path_has_sep =
434 !path.empty() && is_separator(path[path.size() - 1], style);
435 if (path_has_sep) {
436 // Strip separators from beginning of component.
437 size_t loc = component.find_first_not_of(separators(style));
438 StringRef c = component.substr(loc);
439
440 // Append it.
441 path.append(c.begin(), c.end());
442 continue;
443 }
444
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))) {
449 // Add a separator.
450 path.push_back(preferred_separator(style));
451 }
452
453 path.append(component.begin(), component.end());
454 }
455}
456
457void 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);
460}
461
463 const_iterator end, Style style) {
464 for (; begin != end; ++begin)
465 path::append(path, style, *begin);
466}
467
469 size_t end_pos = parent_path_end(path, style);
470 if (end_pos == StringRef::npos)
471 return StringRef();
472 return path.substr(0, end_pos);
473}
474
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);
479}
480
482 Style style) {
483 StringRef p(path.begin(), path.size());
484 SmallString<32> ext_storage;
485 StringRef ext = extension.toStringRef(ext_storage);
486
487 // Erase existing extension.
488 size_t pos = p.find_last_of('.');
489 if (pos != StringRef::npos && pos >= filename_pos(p, style))
490 path.truncate(pos);
491
492 // Append '.' if needed.
493 if (ext.size() > 0 && ext[0] != '.')
494 path.push_back('.');
495
496 // Append extension.
497 path.append(ext.begin(), ext.end());
498}
499
500static 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())
505 return false;
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)
510 return false;
511 if (!SepPath && toLower(Path[I]) != toLower(Prefix[I]))
512 return false;
513 }
514 return true;
515 }
516 return Path.starts_with(Prefix);
517}
518
520 StringRef NewPrefix, Style style) {
521 if (OldPrefix.empty() && NewPrefix.empty())
522 return false;
523
524 StringRef OrigPath(Path.begin(), Path.size());
525 if (!starts_with(OrigPath, OldPrefix, style))
526 return false;
527
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());
531 return true;
532 }
533
534 StringRef RelPath = OrigPath.substr(OldPrefix.size());
535 SmallString<256> NewPath;
536 (Twine(NewPrefix) + RelPath).toVector(NewPath);
537 Path.swap(NewPath);
538 return true;
539}
540
541void 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!");
545 // Clear result.
546 result.clear();
547 path.toVector(result);
548 native(result, style);
549}
550
551std::string native(const Twine &path, Style style) {
552 SmallString<128> Result;
553 native(path, Result, style);
554 return std::string(Result);
555}
556
558 if (Path.empty())
559 return;
560 if (is_style_windows(style)) {
561 for (char &Ch : Path)
562 if (is_separator(Ch, style))
563 Ch = preferred_separator(style);
564 if (Path[0] == '~' && (Path.size() == 1 || is_separator(Path[1], style))) {
565 SmallString<128> PathHome;
566 home_directory(PathHome);
567 PathHome.append(Path.begin() + 1, Path.end());
568 Path = std::move(PathHome);
569 }
570 } else {
571 llvm::replace(Path, '\\', '/');
572 }
573}
574
576 if (is_style_posix(style))
577 return std::string(path);
578
579 std::string s = path.str();
580 llvm::replace(s, '\\', '/');
581 return s;
582}
583
584StringRef filename(StringRef path, Style style) { return *rbegin(path, style); }
585
587 StringRef fname = filename(path, style);
588 size_t pos = fname.find_last_of('.');
589 if (pos == StringRef::npos)
590 return fname;
591 if ((fname.size() == 1 && fname == ".") ||
592 (fname.size() == 2 && fname == ".."))
593 return fname;
594 return fname.substr(0, pos);
595}
596
598 StringRef fname = filename(path, style);
599 size_t pos = fname.find_last_of('.');
600 if (pos == StringRef::npos)
601 return StringRef();
602 if ((fname.size() == 1 && fname == ".") ||
603 (fname.size() == 2 && fname == ".."))
604 return StringRef();
605 return fname.substr(pos);
606}
607
608bool is_separator(char value, Style style) {
609 if (value == '/')
610 return true;
611 if (is_style_windows(style))
612 return value == '\\';
613 return false;
614}
615
617 if (real_style(style) == Style::windows)
618 return "\\";
619 return "/";
620}
621
622bool has_root_name(const Twine &path, Style style) {
623 SmallString<128> path_storage;
624 StringRef p = path.toStringRef(path_storage);
625
626 return !root_name(p, style).empty();
627}
628
629bool has_root_directory(const Twine &path, Style style) {
630 SmallString<128> path_storage;
631 StringRef p = path.toStringRef(path_storage);
632
633 return !root_directory(p, style).empty();
634}
635
636bool has_root_path(const Twine &path, Style style) {
637 SmallString<128> path_storage;
638 StringRef p = path.toStringRef(path_storage);
639
640 return !root_path(p, style).empty();
641}
642
643bool has_relative_path(const Twine &path, Style style) {
644 SmallString<128> path_storage;
645 StringRef p = path.toStringRef(path_storage);
646
647 return !relative_path(p, style).empty();
648}
649
650bool has_filename(const Twine &path, Style style) {
651 SmallString<128> path_storage;
652 StringRef p = path.toStringRef(path_storage);
653
654 return !filename(p, style).empty();
655}
656
657bool has_parent_path(const Twine &path, Style style) {
658 SmallString<128> path_storage;
659 StringRef p = path.toStringRef(path_storage);
660
661 return !parent_path(p, style).empty();
662}
663
664bool has_stem(const Twine &path, Style style) {
665 SmallString<128> path_storage;
666 StringRef p = path.toStringRef(path_storage);
667
668 return !stem(p, style).empty();
669}
670
671bool has_extension(const Twine &path, Style style) {
672 SmallString<128> path_storage;
673 StringRef p = path.toStringRef(path_storage);
674
675 return !extension(p, style).empty();
676}
677
678bool is_absolute(const Twine &path, Style style) {
679 SmallString<128> path_storage;
680 StringRef p = path.toStringRef(path_storage);
681
682 bool rootDir = has_root_directory(p, style);
683 bool rootName = is_style_posix(style) || has_root_name(p, style);
684
685 return rootDir && rootName;
686}
687
688bool is_absolute_gnu(const Twine &path, Style style) {
689 SmallString<128> path_storage;
690 StringRef p = path.toStringRef(path_storage);
691
692 // Handle '/' which is absolute for both Windows and POSIX systems.
693 // Handle '\\' on Windows.
694 if (!p.empty() && is_separator(p.front(), style))
695 return true;
696
697 if (is_style_windows(style)) {
698 // Handle drive letter pattern (a character followed by ':') on Windows.
699 if (p.size() >= 2 && (p[0] && p[1] == ':'))
700 return true;
701 }
702
703 return false;
704}
705
706bool is_relative(const Twine &path, Style style) {
707 return !is_absolute(path, style);
708}
709
710void make_absolute(const Twine &current_directory,
712 StringRef p(path.data(), path.size());
713
714 bool rootDirectory = has_root_directory(p);
715 bool rootName = has_root_name(p);
716
717 // Already absolute.
718 if ((rootName || is_style_posix(Style::native)) && rootDirectory)
719 return;
720
721 // All the following conditions will need the current directory.
722 SmallString<128> current_dir;
723 current_directory.toVector(current_dir);
724
725 // Relative path. Prepend the current directory.
726 if (!rootName && !rootDirectory) {
727 // Append path to the current directory.
728 append(current_dir, p);
729 // Set path to the result.
730 path.swap(current_dir);
731 return;
732 }
733
734 if (!rootName && rootDirectory) {
735 StringRef cdrn = root_name(current_dir);
736 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
737 append(curDirRootName, p);
738 // Set path to the result.
739 path.swap(curDirRootName);
740 return;
741 }
742
743 if (rootName && !rootDirectory) {
744 StringRef pRootName = root_name(p);
745 StringRef bRootDirectory = root_directory(current_dir);
746 StringRef bRelativePath = relative_path(current_dir);
747 StringRef pRelativePath = relative_path(p);
748
750 append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
751 path.swap(res);
752 return;
753 }
754
755 llvm_unreachable("All rootName and rootDirectory combinations should have "
756 "occurred above!");
757}
758
760 // Remove leading "./" (or ".//" or "././" etc.)
761 while (Path.size() > 2 && Path[0] == '.' && is_separator(Path[1], style)) {
762 Path = Path.substr(2);
763 while (Path.size() > 0 && is_separator(Path[0], style))
764 Path = Path.substr(1);
765 }
766 return Path;
767}
768
769bool remove_dots(SmallVectorImpl<char> &the_path, bool remove_dot_dot,
770 Style style) {
771 style = real_style(style);
772 StringRef remaining(the_path.data(), the_path.size());
773 bool needs_change = false;
775
776 // Consume the root path, if present.
777 StringRef root = path::root_path(remaining, style);
778 bool absolute = !root.empty();
779 if (absolute)
780 remaining = remaining.drop_front(root.size());
781
782 // Loop over path components manually. This makes it easier to detect
783 // non-preferred slashes and double separators that must be canonicalized.
784 while (!remaining.empty()) {
785 size_t next_slash = remaining.find_first_of(separators(style));
786 if (next_slash == StringRef::npos)
787 next_slash = remaining.size();
788 StringRef component = remaining.take_front(next_slash);
789 remaining = remaining.drop_front(next_slash);
790
791 // Eat the slash, and check if it is the preferred separator.
792 if (!remaining.empty()) {
793 needs_change |= remaining.front() != preferred_separator(style);
794 remaining = remaining.drop_front();
795 // The path needs to be rewritten if it has a trailing slash.
796 // FIXME: This is emergent behavior that could be removed.
797 needs_change |= remaining.empty();
798 }
799
800 // Check for path traversal components or double separators.
801 if (component.empty() || component == ".") {
802 needs_change = true;
803 } else if (remove_dot_dot && component == "..") {
804 needs_change = true;
805 // Do not allow ".." to remove the root component. If this is the
806 // beginning of a relative path, keep the ".." component.
807 if (!components.empty() && components.back() != "..") {
808 components.pop_back();
809 } else if (!absolute) {
810 components.push_back(component);
811 }
812 } else {
813 components.push_back(component);
814 }
815 }
816
817 SmallString<256> buffer = root;
818 // "root" could be "/", which may need to be translated into "\".
819 make_preferred(buffer, style);
820 needs_change |= root != buffer;
821
822 // Avoid rewriting the path unless we have to.
823 if (!needs_change)
824 return false;
825
826 if (!components.empty()) {
827 buffer += components[0];
828 for (StringRef C : ArrayRef(components).drop_front()) {
829 buffer += preferred_separator(style);
830 buffer += C;
831 }
832 }
833 the_path.swap(buffer);
834 return true;
835}
836
837} // end namespace path
838
839namespace fs {
840
841std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
843
845 std::error_code EC = status(Path, Status);
846 if (EC)
847 return EC;
848 Result = Status.getUniqueID();
849 return std::error_code();
850}
851
852void createUniquePath(const Twine &Model, SmallVectorImpl<char> &ResultPath,
853 bool MakeAbsolute) {
854 SmallString<128> ModelStorage;
855 Model.toVector(ModelStorage);
856
857 assert(llvm::is_contained(ModelStorage, '%') &&
858 "createUniquePath: Model must contain at least one '%'");
859
860 if (MakeAbsolute) {
861 // Make model absolute by prepending a temp directory if it's not already.
862 if (!sys::path::is_absolute(Twine(ModelStorage))) {
863 SmallString<128> TDir;
865 sys::path::append(TDir, Twine(ModelStorage));
866 ModelStorage.swap(TDir);
867 }
868 }
869
870 ResultPath = ModelStorage;
871 ResultPath.push_back(0);
872 ResultPath.pop_back();
873
874 // Replace '%' with random chars.
875 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
876 if (ModelStorage[i] == '%')
877 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
878 }
879}
880
881std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
882 SmallVectorImpl<char> &ResultPath,
883 OpenFlags Flags, unsigned Mode) {
884 return createUniqueEntity(Model, ResultFd, ResultPath, false, FS_File, Flags,
885 Mode);
886}
887
888std::error_code createUniqueFile(const Twine &Model,
889 SmallVectorImpl<char> &ResultPath,
890 unsigned Mode) {
891 int FD;
892 auto EC = createUniqueFile(Model, FD, ResultPath, OF_None, Mode);
893 if (EC)
894 return EC;
895 // FD is only needed to avoid race conditions. Close it right away.
896 close(FD);
897 return EC;
898}
899
900static std::error_code
901createTemporaryFile(const Twine &Model, int &ResultFD,
904 // Any *temporary* file is assumed to be a compiler-internal output, not
905 // a formal one.
906 auto BypassSandbox = sys::sandbox::scopedDisable();
907
908 SmallString<128> Storage;
909 StringRef P = Model.toNullTerminatedStringRef(Storage);
910 assert(P.find_first_of(separators(Style::native)) == StringRef::npos &&
911 "Model must be a simple filename.");
912 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
913 return createUniqueEntity(P.begin(), ResultFD, ResultPath, true, Type, Flags,
915}
916
917static std::error_code
918createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
921 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
922 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
923 Type, Flags);
924}
925
926std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
927 int &ResultFD,
928 SmallVectorImpl<char> &ResultPath,
929 sys::fs::OpenFlags Flags) {
930 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File,
931 Flags);
932}
933
934std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
935 SmallVectorImpl<char> &ResultPath,
936 sys::fs::OpenFlags Flags) {
937 int FD;
938 auto EC = createTemporaryFile(Prefix, Suffix, FD, ResultPath, Flags);
939 if (EC)
940 return EC;
941 // FD is only needed to avoid race conditions. Close it right away.
942 close(FD);
943 return EC;
944}
945
946// This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
947// for consistency. We should try using mkdtemp.
948std::error_code createUniqueDirectory(const Twine &Prefix,
949 SmallVectorImpl<char> &ResultPath) {
950 int Dummy;
951 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath, true,
952 FS_Dir);
953}
954
955std::error_code
957 SmallVectorImpl<char> &ResultPath) {
958 int Dummy;
959 return createUniqueEntity(Model, Dummy, ResultPath, false, FS_Name);
960}
961
962std::error_code
964 SmallVectorImpl<char> &ResultPath) {
965 int Dummy;
966 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
967}
968
971
973 return {};
974
975 SmallString<128> current_dir;
976 if (std::error_code ec = current_path(current_dir))
977 return ec;
978
979 path::make_absolute(current_dir, path);
980 return {};
981}
982
983std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
984 perms Perms) {
985 SmallString<128> PathStorage;
986 StringRef P = Path.toStringRef(PathStorage);
987
988 // Be optimistic and try to create the directory
989 std::error_code EC = create_directory(P, IgnoreExisting, Perms);
990 // If we succeeded, or had any error other than the parent not existing, just
991 // return it.
993 return EC;
994
995 // We failed because of a no_such_file_or_directory, try to create the
996 // parent.
997 StringRef Parent = path::parent_path(P);
998 if (Parent.empty())
999 return EC;
1000
1001 if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
1002 return EC;
1003
1004 return create_directory(P, IgnoreExisting, Perms);
1005}
1006
1007static std::error_code copy_file_internal(int ReadFD, int WriteFD) {
1008 const size_t BufSize = 4096;
1009 char *Buf = new char[BufSize];
1010 int BytesRead = 0, BytesWritten = 0;
1011 for (;;) {
1012 BytesRead = read(ReadFD, Buf, BufSize);
1013 if (BytesRead <= 0)
1014 break;
1015 while (BytesRead) {
1016 BytesWritten = write(WriteFD, Buf, BytesRead);
1017 if (BytesWritten < 0)
1018 break;
1019 BytesRead -= BytesWritten;
1020 }
1021 if (BytesWritten < 0)
1022 break;
1023 }
1024 delete[] Buf;
1025
1026 if (BytesRead < 0 || BytesWritten < 0)
1027 return errnoAsErrorCode();
1028 return std::error_code();
1029}
1030
1031#ifndef __APPLE__
1032std::error_code copy_file(const Twine &From, const Twine &To) {
1033 int ReadFD, WriteFD;
1034 if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
1035 return EC;
1036 if (std::error_code EC =
1037 openFileForWrite(To, WriteFD, CD_CreateAlways, OF_None)) {
1038 close(ReadFD);
1039 return EC;
1040 }
1041
1042 std::error_code EC = copy_file_internal(ReadFD, WriteFD);
1043
1044 close(ReadFD);
1045 close(WriteFD);
1046
1047 return EC;
1048}
1049#endif
1050
1051std::error_code copy_file(const Twine &From, int ToFD) {
1052 int ReadFD;
1053 if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
1054 return EC;
1055
1056 std::error_code EC = copy_file_internal(ReadFD, ToFD);
1057
1058 close(ReadFD);
1059
1060 return EC;
1061}
1062
1065
1066 MD5 Hash;
1067
1068 constexpr size_t BufSize = 4096;
1069 std::vector<uint8_t> Buf(BufSize);
1070 int BytesRead = 0;
1071 for (;;) {
1072 BytesRead = read(FD, Buf.data(), BufSize);
1073 if (BytesRead <= 0)
1074 break;
1075 Hash.update(ArrayRef(Buf.data(), BytesRead));
1076 }
1077
1078 if (BytesRead < 0)
1079 return errnoAsErrorCode();
1080 MD5::MD5Result Result;
1081 Hash.final(Result);
1082 return Result;
1083}
1084
1087
1088 int FD;
1089 if (auto EC = openFileForRead(Path, FD, OF_None))
1090 return EC;
1091
1092 auto Result = md5_contents(FD);
1093 close(FD);
1094 return Result;
1095}
1096
1100
1102 return s.type() != file_type::status_error;
1103}
1104
1105file_type get_file_type(const Twine &Path, bool Follow) {
1106 file_status st;
1107 if (status(Path, st, Follow))
1109 return st.type();
1110}
1111
1113 return status.type() == file_type::directory_file;
1114}
1115
1116std::error_code is_directory(const Twine &path, bool &result) {
1118
1119 file_status st;
1120 if (std::error_code ec = status(path, st))
1121 return ec;
1122 result = is_directory(st);
1123 return std::error_code();
1124}
1125
1127 return status.type() == file_type::regular_file;
1128}
1129
1130std::error_code is_regular_file(const Twine &path, bool &result) {
1132
1133 file_status st;
1134 if (std::error_code ec = status(path, st))
1135 return ec;
1136 result = is_regular_file(st);
1137 return std::error_code();
1138}
1139
1141 return status.type() == file_type::symlink_file;
1142}
1143
1144std::error_code is_symlink_file(const Twine &path, bool &result) {
1146
1147 file_status st;
1148 if (std::error_code ec = status(path, st, false))
1149 return ec;
1150 result = is_symlink_file(st);
1151 return std::error_code();
1152}
1153
1155 return exists(status) &&
1158}
1159
1160std::error_code is_other(const Twine &Path, bool &Result) {
1162
1163 file_status FileStatus;
1164 if (std::error_code EC = status(Path, FileStatus))
1165 return EC;
1166 Result = is_other(FileStatus);
1167 return std::error_code();
1168}
1169
1171 basic_file_status Status) {
1172 SmallString<128> PathStr = path::parent_path(Path);
1173 path::append(PathStr, Filename);
1174 this->Path = std::string(PathStr);
1175 this->Type = Type;
1176 this->Status = Status;
1177}
1178
1181
1183 if (std::error_code EC = status(Path, Status))
1184 return EC;
1185
1186 return Status.permissions();
1187}
1188
1190 assert(Mapping && "Mapping failed but used anyway!");
1191 return Size;
1192}
1193
1195 assert(Mapping && "Mapping failed but used anyway!");
1196 return reinterpret_cast<char *>(Mapping);
1197}
1198
1200 assert(Mapping && "Mapping failed but used anyway!");
1201 return reinterpret_cast<const char *>(Mapping);
1202}
1203
1205 ssize_t ChunkSize) {
1207
1208 // Install a handler to truncate the buffer to the correct size on exit.
1209 size_t Size = Buffer.size();
1210 llvm::scope_exit TruncateOnExit([&]() { Buffer.truncate(Size); });
1211
1212 // Read into Buffer until we hit EOF.
1213 for (;;) {
1214 Buffer.resize_for_overwrite(Size + ChunkSize);
1215 Expected<size_t> ReadBytes = readNativeFile(
1216 FileHandle, MutableArrayRef(Buffer.begin() + Size, ChunkSize));
1217 if (!ReadBytes)
1218 return ReadBytes.takeError();
1219 if (*ReadBytes == 0)
1220 return Error::success();
1221 Size += *ReadBytes;
1222 }
1223}
1224
1225} // end namespace fs
1226} // end namespace sys
1227} // end namespace llvm
1228
1229// Include the truly platform-specific parts.
1230#if defined(LLVM_ON_UNIX)
1231#include "Unix/Path.inc"
1232#endif
1233#if defined(_WIN32)
1234#include "Windows/Path.inc"
1235#endif
1236
1237namespace llvm {
1238namespace sys {
1239namespace fs {
1240
1241TempFile::TempFile(StringRef Name, int FD)
1242 : TmpName(std::string(Name)), FD(FD) {}
1243TempFile::TempFile(TempFile &&Other) { *this = std::move(Other); }
1244TempFile &TempFile::operator=(TempFile &&Other) {
1245 TmpName = std::move(Other.TmpName);
1246 FD = Other.FD;
1247 Other.Done = true;
1248 Other.FD = -1;
1249#ifdef _WIN32
1250 RemoveOnClose = Other.RemoveOnClose;
1251 Other.RemoveOnClose = false;
1252#endif
1253 return *this;
1254}
1255
1257
1259 Done = true;
1260 if (FD != -1 && close(FD) == -1) {
1261 std::error_code EC = errnoAsErrorCode();
1262 return errorCodeToError(EC);
1263 }
1264 FD = -1;
1265
1266#ifdef _WIN32
1267 // On Windows, closing will remove the file, if we set the delete
1268 // disposition. If not, remove it manually.
1269 bool Remove = RemoveOnClose;
1270#else
1271 // Always try to remove the file.
1272 bool Remove = true;
1273#endif
1274 std::error_code RemoveEC;
1275 if (Remove && !TmpName.empty()) {
1276 RemoveEC = fs::remove(TmpName);
1278 if (!RemoveEC)
1279 TmpName = "";
1280 } else {
1281 TmpName = "";
1282 }
1283 return errorCodeToError(RemoveEC);
1284}
1285
1286Error TempFile::keep(const Twine &Name) {
1287 assert(!Done);
1288 Done = true;
1289 // Always try to close and rename.
1290#ifdef _WIN32
1291 // If we can't cancel the delete don't rename.
1292 auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1293 std::error_code RenameEC =
1294 RemoveOnClose ? std::error_code() : setDeleteDisposition(H, false);
1295 bool ShouldDelete = false;
1296 if (!RenameEC) {
1297 RenameEC = rename_handle(H, Name);
1298 // If rename failed because it's cross-device, copy instead
1299 if (RenameEC ==
1300 std::error_code(ERROR_NOT_SAME_DEVICE, std::system_category())) {
1301 RenameEC = copy_file(TmpName, Name);
1302 ShouldDelete = true;
1303 }
1304 }
1305
1306 // If we can't rename or copy, discard the temporary file.
1307 if (RenameEC)
1308 ShouldDelete = true;
1309 if (ShouldDelete) {
1310 if (!RemoveOnClose)
1311 setDeleteDisposition(H, true);
1312 else
1313 remove(TmpName);
1314 }
1315#else
1316 std::error_code RenameEC = fs::rename(TmpName, Name);
1317 if (RenameEC) {
1318 // If we can't rename, try to copy to work around cross-device link issues.
1319 RenameEC = sys::fs::copy_file(TmpName, Name);
1320 // If we can't rename or copy, discard the temporary file.
1321 if (RenameEC)
1322 remove(TmpName);
1323 }
1324#endif
1326
1327 if (!RenameEC)
1328 TmpName = "";
1329
1330 if (close(FD) == -1)
1332 FD = -1;
1333
1334 return errorCodeToError(RenameEC);
1335}
1336
1338 assert(!Done);
1339 Done = true;
1340
1341#ifdef _WIN32
1342 auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1343 if (std::error_code EC = setDeleteDisposition(H, false))
1344 return errorCodeToError(EC);
1345#endif
1347
1348 TmpName = "";
1349
1350 if (close(FD) == -1)
1352 FD = -1;
1353
1354 return Error::success();
1355}
1356
1357Expected<TempFile> TempFile::create(const Twine &Model, unsigned Mode,
1358 OpenFlags ExtraFlags) {
1359 int FD;
1360 SmallString<128> ResultPath;
1361 if (std::error_code EC =
1362 createUniqueFile(Model, FD, ResultPath, OF_Delete | ExtraFlags, Mode))
1363 return errorCodeToError(EC);
1364
1365 TempFile Ret(ResultPath, FD);
1366#ifdef _WIN32
1367 auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1368 bool SetSignalHandler = false;
1369 if (std::error_code EC = setDeleteDisposition(H, true)) {
1370 Ret.RemoveOnClose = true;
1371 SetSignalHandler = true;
1372 }
1373#else
1374 bool SetSignalHandler = true;
1375#endif
1376 if (SetSignalHandler && sys::RemoveFileOnSignal(ResultPath)) {
1377 // Make sure we delete the file when RemoveFileOnSignal fails.
1378 consumeError(Ret.discard());
1379 std::error_code EC(errc::operation_not_permitted);
1380 return errorCodeToError(EC);
1381 }
1382 return std::move(Ret);
1383}
1384} // namespace fs
1385
1386} // namespace sys
1387} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Function Alias Analysis false
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
static constexpr StringLiteral Filename
#define P(N)
static std::error_code createUniqueEntity(const Twine &Model, int &ResultFD, SmallVectorImpl< char > &ResultPath, bool MakeAbsolute, FSEntity Type, sys::fs::OpenFlags Flags=sys::fs::OF_None, unsigned Mode=0)
Definition Path.cpp:171
FSEntity
Definition Path.cpp:164
@ FS_Dir
Definition Path.cpp:165
@ FS_File
Definition Path.cpp:166
@ FS_Name
Definition Path.cpp:167
Provides a library for accessing information about this process and other processes on the operating ...
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file contains some functions that are useful when dealing with strings.
Represents either an error or a value T.
Definition ErrorOr.h:56
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition MD5.cpp:188
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition MD5.cpp:233
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:68
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void resize_for_overwrite(size_type N)
Like resize, but T is POD, the new values won't be initialized.
void truncate(size_type N)
Like resize, but requires that N is less than size().
void swap(SmallVectorImpl &RHS)
void push_back(const T &Elt)
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
static constexpr size_t npos
Definition StringRef.h:57
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:591
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:140
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:629
iterator begin() const
Definition StringRef.h:113
constexpr size_t size() const
size - Get the string size.
Definition StringRef.h:143
char front() const
front - Get the first character in the string.
Definition StringRef.h:146
size_t find_last_of(char C, size_t From=npos) const
Find the last character in the string that is C, or npos if not found.
Definition StringRef.h:421
size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
Definition StringRef.h:396
iterator end() const
Definition StringRef.h:115
StringRef take_front(size_t N=1) const
Return a StringRef equal to 'this' but with only the first N elements remaining.
Definition StringRef.h:600
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
Definition Twine.h:398
StringRef toStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single StringRef if it can be represented as such.
Definition Twine.h:461
LLVM_ABI void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
Definition Twine.cpp:32
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI unsigned GetRandomNumber()
Get the result of a process wide random number generator.
Represents a temporary file.
Definition FileSystem.h:867
LLVM_ABI TempFile & operator=(TempFile &&Other)
Definition Path.cpp:1244
LLVM_ABI Error keep(const Twine &Name)
static LLVM_ABI Expected< TempFile > create(const Twine &Model, unsigned Mode=all_read|all_write, OpenFlags ExtraFlags=OF_None)
This creates a temporary file with createUniqueFile and schedules it for deletion with sys::RemoveFil...
Represents the result of a call to directory_iterator::status().
Definition FileSystem.h:133
LLVM_ABI void replace_filename(const Twine &Filename, file_type Type, basic_file_status Status=basic_file_status())
Definition Path.cpp:1170
Represents the result of a call to sys::fs::status().
Definition FileSystem.h:222
LLVM_ABI size_t size() const
Definition Path.cpp:1189
LLVM_ABI const char * const_data() const
Get a const view of the data.
Definition Path.cpp:1199
LLVM_ABI char * data() const
Definition Path.cpp:1194
LLVM_ABI const_iterator & operator++()
Definition Path.cpp:243
LLVM_ABI bool operator==(const const_iterator &RHS) const
Definition Path.cpp:290
LLVM_ABI ptrdiff_t operator-(const const_iterator &RHS) const
Difference in bytes between this and RHS.
Definition Path.cpp:294
Reverse path iterator.
Definition Path.h:102
LLVM_ABI bool operator==(const reverse_iterator &RHS) const
Definition Path.cpp:340
LLVM_ABI ptrdiff_t operator-(const reverse_iterator &RHS) const
Difference in bytes between this and RHS.
Definition Path.cpp:345
LLVM_ABI reverse_iterator & operator++()
Definition Path.cpp:315
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
iterator end() const
Definition BasicBlock.h:89
value_type read(const void *memory, endianness endian)
Read a value of a particular endianness from memory.
Definition Endian.h:60
LLVM_ABI bool is_regular_file(const basic_file_status &status)
Does status represent a regular file?
Definition Path.cpp:1126
LLVM_ABI bool is_symlink_file(const basic_file_status &status)
Does status represent a symlink file?
Definition Path.cpp:1140
std::error_code openFileForReadWrite(const Twine &Name, int &ResultFD, CreationDisposition Disp, OpenFlags Flags, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
LLVM_ABI std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
LLVM_ABI Error readNativeFileToEOF(file_t FileHandle, SmallVectorImpl< char > &Buffer, ssize_t ChunkSize=DefaultReadChunkSize)
Reads from FileHandle until EOF, appending to Buffer in chunks of size ChunkSize.
Definition Path.cpp:1204
LLVM_ABI ErrorOr< perms > getPermissions(const Twine &Path)
Get file permissions.
Definition Path.cpp:1179
LLVM_ABI std::error_code getPotentiallyUniqueFileName(const Twine &Model, SmallVectorImpl< char > &ResultPath)
Get a unique name, not currently exisiting in the filesystem.
Definition Path.cpp:956
LLVM_ABI std::error_code access(const Twine &Path, AccessMode Mode)
Can the file be accessed?
LLVM_ABI bool is_other(const basic_file_status &status)
Does this status represent something that exists but is not a directory or regular file?
Definition Path.cpp:1154
LLVM_ABI std::error_code getPotentiallyUniqueTempFileName(const Twine &Prefix, StringRef Suffix, SmallVectorImpl< char > &ResultPath)
Get a unique temporary file name, not currently exisiting in the filesystem.
Definition Path.cpp:963
LLVM_ABI Expected< size_t > readNativeFile(file_t FileHandle, MutableArrayRef< char > Buf)
Reads Buf.size() bytes from FileHandle into Buf.
LLVM_ABI bool exists(const basic_file_status &status)
Does file exist?
Definition Path.cpp:1097
@ OF_Delete
The returned handle can be used for deleting the file.
Definition FileSystem.h:793
file_type
An enumeration for the file system's view of the type.
Definition FileSystem.h:62
LLVM_ABI std::error_code getUniqueID(const Twine Path, UniqueID &Result)
Definition Path.cpp:841
LLVM_ABI std::error_code createUniqueFile(const Twine &Model, int &ResultFD, SmallVectorImpl< char > &ResultPath, OpenFlags Flags=OF_None, unsigned Mode=all_read|all_write)
Create a uniquely named file.
Definition Path.cpp:881
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
@ CD_CreateAlways
CD_CreateAlways - When opening a file:
Definition FileSystem.h:749
@ CD_CreateNew
CD_CreateNew - When opening a file:
Definition FileSystem.h:754
LLVM_ABI void createUniquePath(const Twine &Model, SmallVectorImpl< char > &ResultPath, bool MakeAbsolute)
Create a potentially unique file name but does not create it.
Definition Path.cpp:852
std::error_code openFileForWrite(const Twine &Name, int &ResultFD, CreationDisposition Disp=CD_CreateAlways, OpenFlags Flags=OF_None, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
LLVM_ABI std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
Definition Path.cpp:983
LLVM_ABI bool status_known(const basic_file_status &s)
Is status available?
Definition Path.cpp:1101
LLVM_ABI std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, SmallVectorImpl< char > &ResultPath, OpenFlags Flags=OF_None)
Create a file in the system temporary directory.
Definition Path.cpp:926
LLVM_ABI file_type get_file_type(const Twine &Path, bool Follow=true)
Does status represent a directory?
Definition Path.cpp:1105
LLVM_ABI std::error_code make_absolute(SmallVectorImpl< char > &path)
Make path an absolute path.
Definition Path.cpp:969
LLVM_ABI std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
Definition Path.cpp:1032
LLVM_ABI std::error_code createUniqueDirectory(const Twine &Prefix, SmallVectorImpl< char > &ResultPath)
Definition Path.cpp:948
LLVM_ABI std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
LLVM_ABI std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
LLVM_ABI std::error_code create_directory(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create the directory in path.
LLVM_ABI std::error_code openFileForRead(const Twine &Name, int &ResultFD, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
LLVM_ABI ErrorOr< MD5::MD5Result > md5_contents(int FD)
Compute an MD5 hash of a file's contents.
Definition Path.cpp:1063
static std::error_code copy_file_internal(int ReadFD, int WriteFD)
Definition Path.cpp:1007
LLVM_ABI bool is_directory(const basic_file_status &status)
Does status represent a directory?
Definition Path.cpp:1112
LLVM_ABI StringRef get_separator(Style style=Style::native)
Return the preferred separator for this platform.
Definition Path.cpp:616
LLVM_ABI StringRef root_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get root path.
Definition Path.cpp:349
LLVM_ABI void remove_filename(SmallVectorImpl< char > &path, Style style=Style::native)
Remove the last component from path unless it is the root dir.
Definition Path.cpp:475
LLVM_ABI bool has_relative_path(const Twine &path, Style style=Style::native)
Has relative path?
Definition Path.cpp:643
LLVM_ABI StringRef stem(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get stem.
Definition Path.cpp:586
LLVM_ABI bool has_root_name(const Twine &path, Style style=Style::native)
Has root name?
Definition Path.cpp:622
LLVM_ABI void replace_extension(SmallVectorImpl< char > &path, const Twine &extension, Style style=Style::native)
Replace the file extension of path with extension.
Definition Path.cpp:481
LLVM_ABI const_iterator begin(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get begin iterator over path.
Definition Path.cpp:227
LLVM_ABI bool remove_dots(SmallVectorImpl< char > &path, bool remove_dot_dot=false, Style style=Style::native)
Remove '.
Definition Path.cpp:769
LLVM_ABI bool has_root_path(const Twine &path, Style style=Style::native)
Has root path?
Definition Path.cpp:636
constexpr bool is_style_posix(Style S)
Check if S uses POSIX path rules.
Definition Path.h:37
LLVM_ABI StringRef parent_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get parent path.
Definition Path.cpp:468
LLVM_ABI bool has_parent_path(const Twine &path, Style style=Style::native)
Has parent path?
Definition Path.cpp:657
void make_preferred(SmallVectorImpl< char > &path, Style style=Style::native)
For Windows path styles, convert path to use the preferred path separators.
Definition Path.h:286
LLVM_ABI bool is_relative(const Twine &path, Style style=Style::native)
Is path relative?
Definition Path.cpp:706
LLVM_ABI void system_temp_directory(bool erasedOnReboot, SmallVectorImpl< char > &result)
Get the typical temporary directory for the system, e.g., "/var/tmp" or "C:/TEMP".
LLVM_ABI bool has_extension(const Twine &path, Style style=Style::native)
Has extension?
Definition Path.cpp:671
LLVM_ABI void make_absolute(const Twine &current_directory, SmallVectorImpl< char > &path)
Make path an absolute path.
Definition Path.cpp:710
LLVM_ABI bool is_absolute_gnu(const Twine &path, Style style=Style::native)
Is path absolute using GNU rules?
Definition Path.cpp:688
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:584
LLVM_ABI StringRef remove_leading_dotslash(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Remove redundant leading "./" pieces and consecutive separators.
LLVM_ABI std::string convert_to_slash(StringRef path, Style style=Style::native)
Replaces backslashes with slashes if Windows.
Definition Path.cpp:575
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition Path.cpp:678
LLVM_ABI bool has_stem(const Twine &path, Style style=Style::native)
Has stem?
Definition Path.cpp:664
constexpr bool is_style_windows(Style S)
Check if S uses Windows path rules.
Definition Path.h:50
LLVM_ABI StringRef root_name(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get root name.
Definition Path.cpp:374
LLVM_ABI StringRef root_directory(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get root directory.
Definition Path.cpp:391
LLVM_ABI bool replace_path_prefix(SmallVectorImpl< char > &Path, StringRef OldPrefix, StringRef NewPrefix, Style style=Style::native)
Replace matching path prefix with another path.
Definition Path.cpp:519
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:457
LLVM_ABI StringRef extension(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get extension.
Definition Path.cpp:597
LLVM_ABI reverse_iterator rend(StringRef path LLVM_LIFETIME_BOUND)
Get reverse end iterator over path.
LLVM_ABI reverse_iterator rbegin(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get reverse begin iterator over path.
LLVM_ABI bool has_filename(const Twine &path, Style style=Style::native)
Has filename?
Definition Path.cpp:650
LLVM_ABI const_iterator end(StringRef path LLVM_LIFETIME_BOUND)
Get end iterator over path.
Definition Path.cpp:236
LLVM_ABI bool home_directory(SmallVectorImpl< char > &result)
Get the user's home directory.
static bool starts_with(StringRef Path, StringRef Prefix, Style style=Style::native)
Definition Path.cpp:500
LLVM_ABI bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
Definition Path.cpp:608
LLVM_ABI StringRef relative_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get relative path.
Definition Path.cpp:414
LLVM_ABI bool has_root_directory(const Twine &path, Style style=Style::native)
Has root directory?
Definition Path.cpp:629
void violationIfEnabled()
Definition IOSandbox.h:37
ScopedSetting scopedDisable()
Definition IOSandbox.h:36
LLVM_ABI void DontRemoveFileOnSignal(StringRef Filename)
This function removes a file from the list of files to be removed on signal delivery.
LLVM_ABI bool RemoveFileOnSignal(StringRef Filename, std::string *ErrMsg=nullptr)
This function registers signal handlers to ensure that if a signal gets delivered that the named file...
This is an optimization pass for GlobalISel generic memory operations.
char toLower(char x)
Returns the corresponding lowercase character if x is uppercase.
@ Done
Definition Threading.h:60
@ no_such_file_or_directory
Definition Errc.h:65
@ file_exists
Definition Errc.h:48
@ operation_not_permitted
Definition Errc.h:70
@ permission_denied
Definition Errc.h:71
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
@ Other
Any other memory.
Definition ModRef.h:68
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1910
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1885
LLVM_ABI Error write(MCStreamer &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue)
Definition DWP.cpp:677
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
Definition Error.h:1256
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106