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