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