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"
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/IOSandbox.h"
23#include "llvm/Support/Process.h"
24#include "llvm/Support/Signals.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;
38 using llvm::sys::path::is_separator;
39 using llvm::sys::path::Style;
40
41 inline Style real_style(Style style) {
42 if (style != Style::native)
43 return style;
44 if (is_style_posix(S: 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(S: 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(S: style)) {
73 // C:
74 if (path.size() >= 2 &&
75 std::isalpha(static_cast<unsigned char>(path[0])) && path[1] == ':')
76 return path.substr(Start: 0, N: 2);
77 }
78
79 // //net
80 if ((path.size() > 2) && is_separator(value: path[0], style) &&
81 path[0] == path[1] && !is_separator(value: path[2], style)) {
82 // Find the next directory separator.
83 size_t end = path.find_first_of(Chars: separators(style), From: 2);
84 return path.substr(Start: 0, N: end);
85 }
86
87 // {/,\}
88 if (is_separator(value: path[0], style))
89 return path.substr(Start: 0, N: 1);
90
91 // * {file,directory}name
92 size_t end = path.find_first_of(Chars: separators(style));
93 return path.substr(Start: 0, N: 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(value: str[str.size() - 1], style))
100 return str.size() - 1;
101
102 size_t pos = str.find_last_of(Chars: separators(style), From: str.size() - 1);
103
104 if (is_style_windows(S: style)) {
105 if (pos == StringRef::npos)
106 pos = str.find_last_of(C: ':', From: str.size() - 1);
107 }
108
109 if (pos == StringRef::npos || (pos == 1 && is_separator(value: 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(S: style)) {
120 if (str.size() > 2 && str[1] == ':' && is_separator(value: str[2], style))
121 return 2;
122 }
123
124 // case "//net"
125 if (str.size() > 3 && is_separator(value: str[0], style) && str[0] == str[1] &&
126 !is_separator(value: str[2], style)) {
127 return str.find_first_of(Chars: separators(style), From: 2);
128 }
129
130 // case "/"
131 if (str.size() > 0 && is_separator(value: 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(str: path, style);
142
143 bool filename_was_sep =
144 path.size() > 0 && is_separator(value: 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(str: path, style);
148 while (end_pos > 0 &&
149 (root_dir_pos == StringRef::npos || end_pos > root_dir_pos) &&
150 is_separator(value: 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
164enum FSEntity {
165 FS_Dir,
166 FS_File,
167 FS_Name
168};
169
170static std::error_code
171createUniqueEntity(const Twine &Model, int &ResultFD,
172 SmallVectorImpl<char> &ResultPath, bool MakeAbsolute,
173 FSEntity Type, sys::fs::OpenFlags Flags = sys::fs::OF_None,
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(Name: Twine(ResultPath.begin()), ResultFD,
187 Disp: sys::fs::CD_CreateNew, Flags, Mode);
188 if (EC) {
189 // errc::permission_denied happens on Windows when we try to open a file
190 // that has been marked for deletion.
191 if (EC == errc::file_exists || EC == errc::permission_denied)
192 continue;
193 return EC;
194 }
195
196 return std::error_code();
197 }
198
199 case FS_Name: {
200 EC = sys::fs::access(Path: ResultPath.begin(), Mode: sys::fs::AccessMode::Exist);
201 if (EC == errc::no_such_file_or_directory)
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(path: ResultPath.begin(), IgnoreExisting: 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
227const_iterator begin(StringRef path, Style style) {
228 const_iterator i;
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
236const_iterator end(StringRef path) {
237 const_iterator i;
238 i.Path = path;
239 i.Position = path.size();
240 return i;
241}
242
243const_iterator &const_iterator::operator++() {
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(value: Component[0], style: S) &&
258 Component[1] == Component[0] && !is_separator(value: Component[2], style: S);
259
260 // Handle separators.
261 if (is_separator(value: Path[Position], style: S)) {
262 // Root dir.
263 if (was_net ||
264 // c:/
265 (is_style_windows(S) && Component.ends_with(Suffix: ":"))) {
266 Component = Path.substr(Start: Position, N: 1);
267 return *this;
268 }
269
270 // Skip extra separators.
271 while (Position != Path.size() && is_separator(value: Path[Position], style: 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(Chars: separators(style: S), From: Position);
285 Component = Path.slice(Start: Position, End: end_pos);
286
287 return *this;
288}
289
290bool const_iterator::operator==(const const_iterator &RHS) const {
291 return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
292}
293
294ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
295 return Position - RHS.Position;
296}
297
298reverse_iterator rbegin(StringRef Path, Style style) {
299 reverse_iterator I;
300 I.Path = Path;
301 I.Position = Path.size();
302 I.S = style;
303 ++I;
304 return I;
305}
306
307reverse_iterator rend(StringRef Path) {
308 reverse_iterator I;
309 I.Path = Path;
310 I.Component = Path.substr(Start: 0, N: 0);
311 I.Position = 0;
312 return I;
313}
314
315reverse_iterator &reverse_iterator::operator++() {
316 size_t root_dir_pos = root_dir_start(str: Path, style: 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(value: Path[end_pos - 1], style: 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(value: Path.back(), style: 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(str: Path.substr(Start: 0, N: end_pos), style: S);
335 Component = Path.slice(Start: start_pos, End: end_pos);
336 Position = start_pos;
337 return *this;
338}
339
340bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
341 return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
342 Position == RHS.Position;
343}
344
345ptrdiff_t reverse_iterator::operator-(const reverse_iterator &RHS) const {
346 return Position - RHS.Position;
347}
348
349StringRef root_path(StringRef path, Style style) {
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(value: (*b)[0], style) && (*b)[1] == (*b)[0];
354 bool has_drive = is_style_windows(S: style) && b->ends_with(Suffix: ":");
355
356 if (has_net || has_drive) {
357 if ((++pos != e) && is_separator(value: (*pos)[0], style)) {
358 // {C:/,//net/}, so get the first two components.
359 return path.substr(Start: 0, N: 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(value: (*b)[0], style)) {
367 return *b;
368 }
369 }
370
371 return StringRef();
372}
373
374StringRef root_name(StringRef path, Style style) {
375 const_iterator b = begin(path, style), e = end(path);
376 if (b != e) {
377 bool has_net =
378 b->size() > 2 && is_separator(value: (*b)[0], style) && (*b)[1] == (*b)[0];
379 bool has_drive = is_style_windows(S: style) && b->ends_with(Suffix: ":");
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
391StringRef root_directory(StringRef path, Style style) {
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(value: (*b)[0], style) && (*b)[1] == (*b)[0];
396 bool has_drive = is_style_windows(S: style) && b->ends_with(Suffix: ":");
397
398 if ((has_net || has_drive) &&
399 // {C:,//net}, skip to the next component.
400 (++pos != e) && is_separator(value: (*pos)[0], style)) {
401 return *pos;
402 }
403
404 // POSIX style root directory.
405 if (!has_net && is_separator(value: (*b)[0], style)) {
406 return *b;
407 }
408 }
409
410 // No path or no root.
411 return StringRef();
412}
413
414StringRef relative_path(StringRef path, Style style) {
415 StringRef root = root_path(path, style);
416 return path.substr(Start: root.size());
417}
418
419void append(SmallVectorImpl<char> &path, Style style, const Twine &a,
420 const Twine &b, const Twine &c, const Twine &d) {
421 SmallString<32> a_storage;
422 SmallString<32> b_storage;
423 SmallString<32> c_storage;
424 SmallString<32> d_storage;
425
426 SmallVector<StringRef, 4> components;
427 if (!a.isTriviallyEmpty()) components.push_back(Elt: a.toStringRef(Out&: a_storage));
428 if (!b.isTriviallyEmpty()) components.push_back(Elt: b.toStringRef(Out&: b_storage));
429 if (!c.isTriviallyEmpty()) components.push_back(Elt: c.toStringRef(Out&: c_storage));
430 if (!d.isTriviallyEmpty()) components.push_back(Elt: d.toStringRef(Out&: d_storage));
431
432 for (auto &component : components) {
433 bool path_has_sep =
434 !path.empty() && is_separator(value: 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(Chars: separators(style));
438 StringRef c = component.substr(Start: loc);
439
440 // Append it.
441 path.append(in_start: c.begin(), in_end: c.end());
442 continue;
443 }
444
445 bool component_has_sep =
446 !component.empty() && is_separator(value: component[0], style);
447 if (!component_has_sep &&
448 !(path.empty() || has_root_name(path: component, style))) {
449 // Add a separator.
450 path.push_back(Elt: preferred_separator(style));
451 }
452
453 path.append(in_start: component.begin(), in_end: 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: Style::native, a, b, c, d);
460}
461
462void append(SmallVectorImpl<char> &path, const_iterator begin,
463 const_iterator end, Style style) {
464 for (; begin != end; ++begin)
465 path::append(path, style, a: *begin);
466}
467
468StringRef parent_path(StringRef path, Style style) {
469 size_t end_pos = parent_path_end(path, style);
470 if (end_pos == StringRef::npos)
471 return StringRef();
472 return path.substr(Start: 0, N: end_pos);
473}
474
475void remove_filename(SmallVectorImpl<char> &path, Style style) {
476 size_t end_pos = parent_path_end(path: StringRef(path.begin(), path.size()), style);
477 if (end_pos != StringRef::npos)
478 path.truncate(N: end_pos);
479}
480
481void replace_extension(SmallVectorImpl<char> &path, const Twine &extension,
482 Style style) {
483 StringRef p(path.begin(), path.size());
484 SmallString<32> ext_storage;
485 StringRef ext = extension.toStringRef(Out&: ext_storage);
486
487 // Erase existing extension.
488 size_t pos = p.find_last_of(C: '.');
489 if (pos != StringRef::npos && pos >= filename_pos(str: p, style))
490 path.truncate(N: pos);
491
492 // Append '.' if needed.
493 if (ext.size() > 0 && ext[0] != '.')
494 path.push_back(Elt: '.');
495
496 // Append extension.
497 path.append(in_start: ext.begin(), in_end: 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(S: 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(value: Path[I], style);
508 bool SepPrefix = is_separator(value: Prefix[I], style);
509 if (SepPath != SepPrefix)
510 return false;
511 if (!SepPath && toLower(x: Path[I]) != toLower(x: Prefix[I]))
512 return false;
513 }
514 return true;
515 }
516 return Path.starts_with(Prefix);
517}
518
519bool replace_path_prefix(SmallVectorImpl<char> &Path, StringRef OldPrefix,
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(Path: OrigPath, Prefix: 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(Range&: NewPrefix, Out: Path.begin());
531 return true;
532 }
533
534 StringRef RelPath = OrigPath.substr(Start: OldPrefix.size());
535 SmallString<256> NewPath;
536 (Twine(NewPrefix) + RelPath).toVector(Out&: NewPath);
537 Path.swap(RHS&: 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(Out&: result);
548 native(path&: result, style);
549}
550
551void native(SmallVectorImpl<char> &Path, Style style) {
552 if (Path.empty())
553 return;
554 if (is_style_windows(S: style)) {
555 for (char &Ch : Path)
556 if (is_separator(value: Ch, style))
557 Ch = preferred_separator(style);
558 if (Path[0] == '~' && (Path.size() == 1 || is_separator(value: Path[1], style))) {
559 SmallString<128> PathHome;
560 home_directory(result&: PathHome);
561 PathHome.append(in_start: Path.begin() + 1, in_end: Path.end());
562 Path = std::move(PathHome);
563 }
564 } else {
565 llvm::replace(Range&: Path, OldValue: '\\', NewValue: '/');
566 }
567}
568
569std::string convert_to_slash(StringRef path, Style style) {
570 if (is_style_posix(S: style))
571 return std::string(path);
572
573 std::string s = path.str();
574 llvm::replace(Range&: s, OldValue: '\\', NewValue: '/');
575 return s;
576}
577
578StringRef filename(StringRef path, Style style) { return *rbegin(Path: path, style); }
579
580StringRef stem(StringRef path, Style style) {
581 StringRef fname = filename(path, style);
582 size_t pos = fname.find_last_of(C: '.');
583 if (pos == StringRef::npos)
584 return fname;
585 if ((fname.size() == 1 && fname == ".") ||
586 (fname.size() == 2 && fname == ".."))
587 return fname;
588 return fname.substr(Start: 0, N: pos);
589}
590
591StringRef extension(StringRef path, Style style) {
592 StringRef fname = filename(path, style);
593 size_t pos = fname.find_last_of(C: '.');
594 if (pos == StringRef::npos)
595 return StringRef();
596 if ((fname.size() == 1 && fname == ".") ||
597 (fname.size() == 2 && fname == ".."))
598 return StringRef();
599 return fname.substr(Start: pos);
600}
601
602bool is_separator(char value, Style style) {
603 if (value == '/')
604 return true;
605 if (is_style_windows(S: style))
606 return value == '\\';
607 return false;
608}
609
610StringRef get_separator(Style style) {
611 if (real_style(style) == Style::windows)
612 return "\\";
613 return "/";
614}
615
616bool has_root_name(const Twine &path, Style style) {
617 SmallString<128> path_storage;
618 StringRef p = path.toStringRef(Out&: path_storage);
619
620 return !root_name(path: p, style).empty();
621}
622
623bool has_root_directory(const Twine &path, Style style) {
624 SmallString<128> path_storage;
625 StringRef p = path.toStringRef(Out&: path_storage);
626
627 return !root_directory(path: p, style).empty();
628}
629
630bool has_root_path(const Twine &path, Style style) {
631 SmallString<128> path_storage;
632 StringRef p = path.toStringRef(Out&: path_storage);
633
634 return !root_path(path: p, style).empty();
635}
636
637bool has_relative_path(const Twine &path, Style style) {
638 SmallString<128> path_storage;
639 StringRef p = path.toStringRef(Out&: path_storage);
640
641 return !relative_path(path: p, style).empty();
642}
643
644bool has_filename(const Twine &path, Style style) {
645 SmallString<128> path_storage;
646 StringRef p = path.toStringRef(Out&: path_storage);
647
648 return !filename(path: p, style).empty();
649}
650
651bool has_parent_path(const Twine &path, Style style) {
652 SmallString<128> path_storage;
653 StringRef p = path.toStringRef(Out&: path_storage);
654
655 return !parent_path(path: p, style).empty();
656}
657
658bool has_stem(const Twine &path, Style style) {
659 SmallString<128> path_storage;
660 StringRef p = path.toStringRef(Out&: path_storage);
661
662 return !stem(path: p, style).empty();
663}
664
665bool has_extension(const Twine &path, Style style) {
666 SmallString<128> path_storage;
667 StringRef p = path.toStringRef(Out&: path_storage);
668
669 return !extension(path: p, style).empty();
670}
671
672bool is_absolute(const Twine &path, Style style) {
673 SmallString<128> path_storage;
674 StringRef p = path.toStringRef(Out&: path_storage);
675
676 bool rootDir = has_root_directory(path: p, style);
677 bool rootName = is_style_posix(S: style) || has_root_name(path: p, style);
678
679 return rootDir && rootName;
680}
681
682bool is_absolute_gnu(const Twine &path, Style style) {
683 SmallString<128> path_storage;
684 StringRef p = path.toStringRef(Out&: path_storage);
685
686 // Handle '/' which is absolute for both Windows and POSIX systems.
687 // Handle '\\' on Windows.
688 if (!p.empty() && is_separator(value: p.front(), style))
689 return true;
690
691 if (is_style_windows(S: style)) {
692 // Handle drive letter pattern (a character followed by ':') on Windows.
693 if (p.size() >= 2 && (p[0] && p[1] == ':'))
694 return true;
695 }
696
697 return false;
698}
699
700bool is_relative(const Twine &path, Style style) {
701 return !is_absolute(path, style);
702}
703
704void make_absolute(const Twine &current_directory,
705 SmallVectorImpl<char> &path) {
706 StringRef p(path.data(), path.size());
707
708 bool rootDirectory = has_root_directory(path: p);
709 bool rootName = has_root_name(path: p);
710
711 // Already absolute.
712 if ((rootName || is_style_posix(S: Style::native)) && rootDirectory)
713 return;
714
715 // All the following conditions will need the current directory.
716 SmallString<128> current_dir;
717 current_directory.toVector(Out&: current_dir);
718
719 // Relative path. Prepend the current directory.
720 if (!rootName && !rootDirectory) {
721 // Append path to the current directory.
722 append(path&: current_dir, a: p);
723 // Set path to the result.
724 path.swap(RHS&: current_dir);
725 return;
726 }
727
728 if (!rootName && rootDirectory) {
729 StringRef cdrn = root_name(path: current_dir);
730 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
731 append(path&: curDirRootName, a: p);
732 // Set path to the result.
733 path.swap(RHS&: curDirRootName);
734 return;
735 }
736
737 if (rootName && !rootDirectory) {
738 StringRef pRootName = root_name(path: p);
739 StringRef bRootDirectory = root_directory(path: current_dir);
740 StringRef bRelativePath = relative_path(path: current_dir);
741 StringRef pRelativePath = relative_path(path: p);
742
743 SmallString<128> res;
744 append(path&: res, a: pRootName, b: bRootDirectory, c: bRelativePath, d: pRelativePath);
745 path.swap(RHS&: res);
746 return;
747 }
748
749 llvm_unreachable("All rootName and rootDirectory combinations should have "
750 "occurred above!");
751}
752
753StringRef remove_leading_dotslash(StringRef Path, Style style) {
754 // Remove leading "./" (or ".//" or "././" etc.)
755 while (Path.size() > 2 && Path[0] == '.' && is_separator(value: Path[1], style)) {
756 Path = Path.substr(Start: 2);
757 while (Path.size() > 0 && is_separator(value: Path[0], style))
758 Path = Path.substr(Start: 1);
759 }
760 return Path;
761}
762
763// Remove path traversal components ("." and "..") when possible, and
764// canonicalize slashes.
765bool remove_dots(SmallVectorImpl<char> &the_path, bool remove_dot_dot,
766 Style style) {
767 style = real_style(style);
768 StringRef remaining(the_path.data(), the_path.size());
769 bool needs_change = false;
770 SmallVector<StringRef, 16> components;
771
772 // Consume the root path, if present.
773 StringRef root = path::root_path(path: remaining, style);
774 bool absolute = !root.empty();
775 if (absolute)
776 remaining = remaining.drop_front(N: root.size());
777
778 // Loop over path components manually. This makes it easier to detect
779 // non-preferred slashes and double separators that must be canonicalized.
780 while (!remaining.empty()) {
781 size_t next_slash = remaining.find_first_of(Chars: separators(style));
782 if (next_slash == StringRef::npos)
783 next_slash = remaining.size();
784 StringRef component = remaining.take_front(N: next_slash);
785 remaining = remaining.drop_front(N: next_slash);
786
787 // Eat the slash, and check if it is the preferred separator.
788 if (!remaining.empty()) {
789 needs_change |= remaining.front() != preferred_separator(style);
790 remaining = remaining.drop_front();
791 // The path needs to be rewritten if it has a trailing slash.
792 // FIXME: This is emergent behavior that could be removed.
793 needs_change |= remaining.empty();
794 }
795
796 // Check for path traversal components or double separators.
797 if (component.empty() || component == ".") {
798 needs_change = true;
799 } else if (remove_dot_dot && component == "..") {
800 needs_change = true;
801 // Do not allow ".." to remove the root component. If this is the
802 // beginning of a relative path, keep the ".." component.
803 if (!components.empty() && components.back() != "..") {
804 components.pop_back();
805 } else if (!absolute) {
806 components.push_back(Elt: component);
807 }
808 } else {
809 components.push_back(Elt: component);
810 }
811 }
812
813 SmallString<256> buffer = root;
814 // "root" could be "/", which may need to be translated into "\".
815 make_preferred(path&: buffer, style);
816 needs_change |= root != buffer;
817
818 // Avoid rewriting the path unless we have to.
819 if (!needs_change)
820 return false;
821
822 if (!components.empty()) {
823 buffer += components[0];
824 for (StringRef C : ArrayRef(components).drop_front()) {
825 buffer += preferred_separator(style);
826 buffer += C;
827 }
828 }
829 the_path.swap(RHS&: buffer);
830 return true;
831}
832
833} // end namespace path
834
835namespace fs {
836
837std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
838 sandbox::violationIfEnabled();
839
840 file_status Status;
841 std::error_code EC = status(path: Path, result&: Status);
842 if (EC)
843 return EC;
844 Result = Status.getUniqueID();
845 return std::error_code();
846}
847
848void createUniquePath(const Twine &Model, SmallVectorImpl<char> &ResultPath,
849 bool MakeAbsolute) {
850 SmallString<128> ModelStorage;
851 Model.toVector(Out&: ModelStorage);
852
853 if (MakeAbsolute) {
854 // Make model absolute by prepending a temp directory if it's not already.
855 if (!sys::path::is_absolute(path: Twine(ModelStorage))) {
856 SmallString<128> TDir;
857 sys::path::system_temp_directory(erasedOnReboot: true, result&: TDir);
858 sys::path::append(path&: TDir, a: Twine(ModelStorage));
859 ModelStorage.swap(RHS&: TDir);
860 }
861 }
862
863 ResultPath = ModelStorage;
864 ResultPath.push_back(Elt: 0);
865 ResultPath.pop_back();
866
867 // Replace '%' with random chars.
868 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
869 if (ModelStorage[i] == '%')
870 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
871 }
872}
873
874std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
875 SmallVectorImpl<char> &ResultPath,
876 OpenFlags Flags, unsigned Mode) {
877 return createUniqueEntity(Model, ResultFD&: ResultFd, ResultPath, MakeAbsolute: false, Type: FS_File, Flags,
878 Mode);
879}
880
881std::error_code createUniqueFile(const Twine &Model,
882 SmallVectorImpl<char> &ResultPath,
883 unsigned Mode) {
884 int FD;
885 auto EC = createUniqueFile(Model, ResultFd&: FD, ResultPath, Flags: OF_None, Mode);
886 if (EC)
887 return EC;
888 // FD is only needed to avoid race conditions. Close it right away.
889 close(fd: FD);
890 return EC;
891}
892
893static std::error_code
894createTemporaryFile(const Twine &Model, int &ResultFD,
895 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type,
896 sys::fs::OpenFlags Flags = sys::fs::OF_None) {
897 // Any *temporary* file is assumed to be a compiler-internal output, not
898 // a formal one.
899 auto BypassSandbox = sys::sandbox::scopedDisable();
900
901 SmallString<128> Storage;
902 StringRef P = Model.toNullTerminatedStringRef(Out&: Storage);
903 assert(P.find_first_of(separators(Style::native)) == StringRef::npos &&
904 "Model must be a simple filename.");
905 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
906 return createUniqueEntity(Model: P.begin(), ResultFD, ResultPath, MakeAbsolute: true, Type, Flags,
907 Mode: all_read | all_write);
908}
909
910static std::error_code
911createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
912 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type,
913 sys::fs::OpenFlags Flags = sys::fs::OF_None) {
914 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
915 return createTemporaryFile(Model: Prefix + Middle + Suffix, ResultFD, ResultPath,
916 Type, Flags);
917}
918
919std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
920 int &ResultFD,
921 SmallVectorImpl<char> &ResultPath,
922 sys::fs::OpenFlags Flags) {
923 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, Type: FS_File,
924 Flags);
925}
926
927std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
928 SmallVectorImpl<char> &ResultPath,
929 sys::fs::OpenFlags Flags) {
930 int FD;
931 auto EC = createTemporaryFile(Prefix, Suffix, ResultFD&: FD, ResultPath, Flags);
932 if (EC)
933 return EC;
934 // FD is only needed to avoid race conditions. Close it right away.
935 close(fd: FD);
936 return EC;
937}
938
939// This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
940// for consistency. We should try using mkdtemp.
941std::error_code createUniqueDirectory(const Twine &Prefix,
942 SmallVectorImpl<char> &ResultPath) {
943 int Dummy;
944 return createUniqueEntity(Model: Prefix + "-%%%%%%", ResultFD&: Dummy, ResultPath, MakeAbsolute: true,
945 Type: FS_Dir);
946}
947
948std::error_code
949getPotentiallyUniqueFileName(const Twine &Model,
950 SmallVectorImpl<char> &ResultPath) {
951 int Dummy;
952 return createUniqueEntity(Model, ResultFD&: Dummy, ResultPath, MakeAbsolute: false, Type: FS_Name);
953}
954
955std::error_code
956getPotentiallyUniqueTempFileName(const Twine &Prefix, StringRef Suffix,
957 SmallVectorImpl<char> &ResultPath) {
958 int Dummy;
959 return createTemporaryFile(Prefix, Suffix, ResultFD&: Dummy, ResultPath, Type: FS_Name);
960}
961
962std::error_code make_absolute(SmallVectorImpl<char> &path) {
963 sandbox::violationIfEnabled();
964
965 if (path::is_absolute(path))
966 return {};
967
968 SmallString<128> current_dir;
969 if (std::error_code ec = current_path(result&: current_dir))
970 return ec;
971
972 path::make_absolute(current_directory: current_dir, path);
973 return {};
974}
975
976std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
977 perms Perms) {
978 SmallString<128> PathStorage;
979 StringRef P = Path.toStringRef(Out&: PathStorage);
980
981 // Be optimistic and try to create the directory
982 std::error_code EC = create_directory(path: P, IgnoreExisting, Perms);
983 // If we succeeded, or had any error other than the parent not existing, just
984 // return it.
985 if (EC != errc::no_such_file_or_directory)
986 return EC;
987
988 // We failed because of a no_such_file_or_directory, try to create the
989 // parent.
990 StringRef Parent = path::parent_path(path: P);
991 if (Parent.empty())
992 return EC;
993
994 if ((EC = create_directories(Path: Parent, IgnoreExisting, Perms)))
995 return EC;
996
997 return create_directory(path: P, IgnoreExisting, Perms);
998}
999
1000static std::error_code copy_file_internal(int ReadFD, int WriteFD) {
1001 const size_t BufSize = 4096;
1002 char *Buf = new char[BufSize];
1003 int BytesRead = 0, BytesWritten = 0;
1004 for (;;) {
1005 BytesRead = read(fd: ReadFD, buf: Buf, nbytes: BufSize);
1006 if (BytesRead <= 0)
1007 break;
1008 while (BytesRead) {
1009 BytesWritten = write(fd: WriteFD, buf: Buf, n: BytesRead);
1010 if (BytesWritten < 0)
1011 break;
1012 BytesRead -= BytesWritten;
1013 }
1014 if (BytesWritten < 0)
1015 break;
1016 }
1017 delete[] Buf;
1018
1019 if (BytesRead < 0 || BytesWritten < 0)
1020 return errnoAsErrorCode();
1021 return std::error_code();
1022}
1023
1024#ifndef __APPLE__
1025std::error_code copy_file(const Twine &From, const Twine &To) {
1026 int ReadFD, WriteFD;
1027 if (std::error_code EC = openFileForRead(Name: From, ResultFD&: ReadFD, Flags: OF_None))
1028 return EC;
1029 if (std::error_code EC =
1030 openFileForWrite(Name: To, ResultFD&: WriteFD, Disp: CD_CreateAlways, Flags: OF_None)) {
1031 close(fd: ReadFD);
1032 return EC;
1033 }
1034
1035 std::error_code EC = copy_file_internal(ReadFD, WriteFD);
1036
1037 close(fd: ReadFD);
1038 close(fd: WriteFD);
1039
1040 return EC;
1041}
1042#endif
1043
1044std::error_code copy_file(const Twine &From, int ToFD) {
1045 int ReadFD;
1046 if (std::error_code EC = openFileForRead(Name: From, ResultFD&: ReadFD, Flags: OF_None))
1047 return EC;
1048
1049 std::error_code EC = copy_file_internal(ReadFD, WriteFD: ToFD);
1050
1051 close(fd: ReadFD);
1052
1053 return EC;
1054}
1055
1056ErrorOr<MD5::MD5Result> md5_contents(int FD) {
1057 sandbox::violationIfEnabled();
1058
1059 MD5 Hash;
1060
1061 constexpr size_t BufSize = 4096;
1062 std::vector<uint8_t> Buf(BufSize);
1063 int BytesRead = 0;
1064 for (;;) {
1065 BytesRead = read(fd: FD, buf: Buf.data(), nbytes: BufSize);
1066 if (BytesRead <= 0)
1067 break;
1068 Hash.update(Data: ArrayRef(Buf.data(), BytesRead));
1069 }
1070
1071 if (BytesRead < 0)
1072 return errnoAsErrorCode();
1073 MD5::MD5Result Result;
1074 Hash.final(Result);
1075 return Result;
1076}
1077
1078ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path) {
1079 sandbox::violationIfEnabled();
1080
1081 int FD;
1082 if (auto EC = openFileForRead(Name: Path, ResultFD&: FD, Flags: OF_None))
1083 return EC;
1084
1085 auto Result = md5_contents(FD);
1086 close(fd: FD);
1087 return Result;
1088}
1089
1090bool exists(const basic_file_status &status) {
1091 return status_known(s: status) && status.type() != file_type::file_not_found;
1092}
1093
1094bool status_known(const basic_file_status &s) {
1095 return s.type() != file_type::status_error;
1096}
1097
1098file_type get_file_type(const Twine &Path, bool Follow) {
1099 file_status st;
1100 if (status(path: Path, result&: st, follow: Follow))
1101 return file_type::status_error;
1102 return st.type();
1103}
1104
1105bool is_directory(const basic_file_status &status) {
1106 return status.type() == file_type::directory_file;
1107}
1108
1109std::error_code is_directory(const Twine &path, bool &result) {
1110 sandbox::violationIfEnabled();
1111
1112 file_status st;
1113 if (std::error_code ec = status(path, result&: st))
1114 return ec;
1115 result = is_directory(status: st);
1116 return std::error_code();
1117}
1118
1119bool is_regular_file(const basic_file_status &status) {
1120 return status.type() == file_type::regular_file;
1121}
1122
1123std::error_code is_regular_file(const Twine &path, bool &result) {
1124 sandbox::violationIfEnabled();
1125
1126 file_status st;
1127 if (std::error_code ec = status(path, result&: st))
1128 return ec;
1129 result = is_regular_file(status: st);
1130 return std::error_code();
1131}
1132
1133bool is_symlink_file(const basic_file_status &status) {
1134 return status.type() == file_type::symlink_file;
1135}
1136
1137std::error_code is_symlink_file(const Twine &path, bool &result) {
1138 sandbox::violationIfEnabled();
1139
1140 file_status st;
1141 if (std::error_code ec = status(path, result&: st, follow: false))
1142 return ec;
1143 result = is_symlink_file(status: st);
1144 return std::error_code();
1145}
1146
1147bool is_other(const basic_file_status &status) {
1148 return exists(status) &&
1149 !is_regular_file(status) &&
1150 !is_directory(status);
1151}
1152
1153std::error_code is_other(const Twine &Path, bool &Result) {
1154 sandbox::violationIfEnabled();
1155
1156 file_status FileStatus;
1157 if (std::error_code EC = status(path: Path, result&: FileStatus))
1158 return EC;
1159 Result = is_other(status: FileStatus);
1160 return std::error_code();
1161}
1162
1163void directory_entry::replace_filename(const Twine &Filename, file_type Type,
1164 basic_file_status Status) {
1165 SmallString<128> PathStr = path::parent_path(path: Path);
1166 path::append(path&: PathStr, a: Filename);
1167 this->Path = std::string(PathStr);
1168 this->Type = Type;
1169 this->Status = Status;
1170}
1171
1172ErrorOr<perms> getPermissions(const Twine &Path) {
1173 sandbox::violationIfEnabled();
1174
1175 file_status Status;
1176 if (std::error_code EC = status(path: Path, result&: Status))
1177 return EC;
1178
1179 return Status.permissions();
1180}
1181
1182size_t mapped_file_region::size() const {
1183 assert(Mapping && "Mapping failed but used anyway!");
1184 return Size;
1185}
1186
1187char *mapped_file_region::data() const {
1188 assert(Mapping && "Mapping failed but used anyway!");
1189 return reinterpret_cast<char *>(Mapping);
1190}
1191
1192const char *mapped_file_region::const_data() const {
1193 assert(Mapping && "Mapping failed but used anyway!");
1194 return reinterpret_cast<const char *>(Mapping);
1195}
1196
1197Error readNativeFileToEOF(file_t FileHandle, SmallVectorImpl<char> &Buffer,
1198 ssize_t ChunkSize) {
1199 sandbox::violationIfEnabled();
1200
1201 // Install a handler to truncate the buffer to the correct size on exit.
1202 size_t Size = Buffer.size();
1203 llvm::scope_exit TruncateOnExit([&]() { Buffer.truncate(N: Size); });
1204
1205 // Read into Buffer until we hit EOF.
1206 for (;;) {
1207 Buffer.resize_for_overwrite(N: Size + ChunkSize);
1208 Expected<size_t> ReadBytes = readNativeFile(
1209 FileHandle, Buf: MutableArrayRef(Buffer.begin() + Size, ChunkSize));
1210 if (!ReadBytes)
1211 return ReadBytes.takeError();
1212 if (*ReadBytes == 0)
1213 return Error::success();
1214 Size += *ReadBytes;
1215 }
1216}
1217
1218} // end namespace fs
1219} // end namespace sys
1220} // end namespace llvm
1221
1222// Include the truly platform-specific parts.
1223#if defined(LLVM_ON_UNIX)
1224#include "Unix/Path.inc"
1225#endif
1226#if defined(_WIN32)
1227#include "Windows/Path.inc"
1228#endif
1229
1230namespace llvm {
1231namespace sys {
1232namespace fs {
1233
1234TempFile::TempFile(StringRef Name, int FD)
1235 : TmpName(std::string(Name)), FD(FD) {}
1236TempFile::TempFile(TempFile &&Other) { *this = std::move(Other); }
1237TempFile &TempFile::operator=(TempFile &&Other) {
1238 TmpName = std::move(Other.TmpName);
1239 FD = Other.FD;
1240 Other.Done = true;
1241 Other.FD = -1;
1242#ifdef _WIN32
1243 RemoveOnClose = Other.RemoveOnClose;
1244 Other.RemoveOnClose = false;
1245#endif
1246 return *this;
1247}
1248
1249TempFile::~TempFile() { assert(Done); }
1250
1251Error TempFile::discard() {
1252 Done = true;
1253 if (FD != -1 && close(fd: FD) == -1) {
1254 std::error_code EC = errnoAsErrorCode();
1255 return errorCodeToError(EC);
1256 }
1257 FD = -1;
1258
1259#ifdef _WIN32
1260 // On Windows, closing will remove the file, if we set the delete
1261 // disposition. If not, remove it manually.
1262 bool Remove = RemoveOnClose;
1263#else
1264 // Always try to remove the file.
1265 bool Remove = true;
1266#endif
1267 std::error_code RemoveEC;
1268 if (Remove && !TmpName.empty()) {
1269 RemoveEC = fs::remove(path: TmpName);
1270 sys::DontRemoveFileOnSignal(Filename: TmpName);
1271 if (!RemoveEC)
1272 TmpName = "";
1273 } else {
1274 TmpName = "";
1275 }
1276 return errorCodeToError(EC: RemoveEC);
1277}
1278
1279Error TempFile::keep(const Twine &Name) {
1280 assert(!Done);
1281 Done = true;
1282 // Always try to close and rename.
1283#ifdef _WIN32
1284 // If we can't cancel the delete don't rename.
1285 auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1286 std::error_code RenameEC =
1287 RemoveOnClose ? std::error_code() : setDeleteDisposition(H, false);
1288 bool ShouldDelete = false;
1289 if (!RenameEC) {
1290 RenameEC = rename_handle(H, Name);
1291 // If rename failed because it's cross-device, copy instead
1292 if (RenameEC ==
1293 std::error_code(ERROR_NOT_SAME_DEVICE, std::system_category())) {
1294 RenameEC = copy_file(TmpName, Name);
1295 ShouldDelete = true;
1296 }
1297 }
1298
1299 // If we can't rename or copy, discard the temporary file.
1300 if (RenameEC)
1301 ShouldDelete = true;
1302 if (ShouldDelete) {
1303 if (!RemoveOnClose)
1304 setDeleteDisposition(H, true);
1305 else
1306 remove(TmpName);
1307 }
1308#else
1309 std::error_code RenameEC = fs::rename(from: TmpName, to: Name);
1310 if (RenameEC) {
1311 // If we can't rename, try to copy to work around cross-device link issues.
1312 RenameEC = sys::fs::copy_file(From: TmpName, To: Name);
1313 // If we can't rename or copy, discard the temporary file.
1314 if (RenameEC)
1315 remove(path: TmpName);
1316 }
1317#endif
1318 sys::DontRemoveFileOnSignal(Filename: TmpName);
1319
1320 if (!RenameEC)
1321 TmpName = "";
1322
1323 if (close(fd: FD) == -1)
1324 return errorCodeToError(EC: errnoAsErrorCode());
1325 FD = -1;
1326
1327 return errorCodeToError(EC: RenameEC);
1328}
1329
1330Error TempFile::keep() {
1331 assert(!Done);
1332 Done = true;
1333
1334#ifdef _WIN32
1335 auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1336 if (std::error_code EC = setDeleteDisposition(H, false))
1337 return errorCodeToError(EC);
1338#endif
1339 sys::DontRemoveFileOnSignal(Filename: TmpName);
1340
1341 TmpName = "";
1342
1343 if (close(fd: FD) == -1)
1344 return errorCodeToError(EC: errnoAsErrorCode());
1345 FD = -1;
1346
1347 return Error::success();
1348}
1349
1350Expected<TempFile> TempFile::create(const Twine &Model, unsigned Mode,
1351 OpenFlags ExtraFlags) {
1352 int FD;
1353 SmallString<128> ResultPath;
1354 if (std::error_code EC =
1355 createUniqueFile(Model, ResultFd&: FD, ResultPath, Flags: OF_Delete | ExtraFlags, Mode))
1356 return errorCodeToError(EC);
1357
1358 TempFile Ret(ResultPath, FD);
1359#ifdef _WIN32
1360 auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1361 bool SetSignalHandler = false;
1362 if (std::error_code EC = setDeleteDisposition(H, true)) {
1363 Ret.RemoveOnClose = true;
1364 SetSignalHandler = true;
1365 }
1366#else
1367 bool SetSignalHandler = true;
1368#endif
1369 if (SetSignalHandler && sys::RemoveFileOnSignal(Filename: ResultPath)) {
1370 // Make sure we delete the file when RemoveFileOnSignal fails.
1371 consumeError(Err: Ret.discard());
1372 std::error_code EC(errc::operation_not_permitted);
1373 return errorCodeToError(EC);
1374 }
1375 return std::move(Ret);
1376}
1377} // namespace fs
1378
1379} // namespace sys
1380} // namespace llvm
1381