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