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     if (style != Style::native)
41       return style;
42     if (is_style_posix(style))
43       return Style::posix;
44     return Style::windows;
45   }
46 
47   inline const char *separators(Style style) {
48     if (is_style_windows(style))
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 (is_style_windows(style)) {
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 (is_style_windows(style)) {
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 (is_style_windows(style)) {
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                    FSEntity Type, sys::fs::OpenFlags Flags = sys::fs::OF_None,
171                    unsigned Mode = 0) {
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         (is_style_windows(S) && 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 = is_style_windows(style) && 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       }
358       // just {C:,//net}, return the first component.
359       return *b;
360     }
361 
362     // POSIX style root directory.
363     if (is_separator((*b)[0], style)) {
364       return *b;
365     }
366   }
367 
368   return StringRef();
369 }
370 
371 StringRef root_name(StringRef path, Style style) {
372   const_iterator b = begin(path, style), e = end(path);
373   if (b != e) {
374     bool has_net =
375         b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
376     bool has_drive = is_style_windows(style) && b->endswith(":");
377 
378     if (has_net || has_drive) {
379       // just {C:,//net}, return the first component.
380       return *b;
381     }
382   }
383 
384   // No path or no name.
385   return StringRef();
386 }
387 
388 StringRef root_directory(StringRef path, Style style) {
389   const_iterator b = begin(path, style), pos = b, e = end(path);
390   if (b != e) {
391     bool has_net =
392         b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
393     bool has_drive = is_style_windows(style) && b->endswith(":");
394 
395     if ((has_net || has_drive) &&
396         // {C:,//net}, skip to the next component.
397         (++pos != e) && is_separator((*pos)[0], style)) {
398       return *pos;
399     }
400 
401     // POSIX style root directory.
402     if (!has_net && is_separator((*b)[0], style)) {
403       return *b;
404     }
405   }
406 
407   // No path or no root.
408   return StringRef();
409 }
410 
411 StringRef relative_path(StringRef path, Style style) {
412   StringRef root = root_path(path, style);
413   return path.substr(root.size());
414 }
415 
416 void append(SmallVectorImpl<char> &path, Style style, const Twine &a,
417             const Twine &b, const Twine &c, const Twine &d) {
418   SmallString<32> a_storage;
419   SmallString<32> b_storage;
420   SmallString<32> c_storage;
421   SmallString<32> d_storage;
422 
423   SmallVector<StringRef, 4> components;
424   if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
425   if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
426   if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
427   if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
428 
429   for (auto &component : components) {
430     bool path_has_sep =
431         !path.empty() && is_separator(path[path.size() - 1], style);
432     if (path_has_sep) {
433       // Strip separators from beginning of component.
434       size_t loc = component.find_first_not_of(separators(style));
435       StringRef c = component.substr(loc);
436 
437       // Append it.
438       path.append(c.begin(), c.end());
439       continue;
440     }
441 
442     bool component_has_sep =
443         !component.empty() && is_separator(component[0], style);
444     if (!component_has_sep &&
445         !(path.empty() || has_root_name(component, style))) {
446       // Add a separator.
447       path.push_back(preferred_separator(style));
448     }
449 
450     path.append(component.begin(), component.end());
451   }
452 }
453 
454 void append(SmallVectorImpl<char> &path, const Twine &a, const Twine &b,
455             const Twine &c, const Twine &d) {
456   append(path, Style::native, a, b, c, d);
457 }
458 
459 void append(SmallVectorImpl<char> &path, const_iterator begin,
460             const_iterator end, Style style) {
461   for (; begin != end; ++begin)
462     path::append(path, style, *begin);
463 }
464 
465 StringRef parent_path(StringRef path, Style style) {
466   size_t end_pos = parent_path_end(path, style);
467   if (end_pos == StringRef::npos)
468     return StringRef();
469   return path.substr(0, end_pos);
470 }
471 
472 void remove_filename(SmallVectorImpl<char> &path, Style style) {
473   size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()), style);
474   if (end_pos != StringRef::npos)
475     path.set_size(end_pos);
476 }
477 
478 void replace_extension(SmallVectorImpl<char> &path, const Twine &extension,
479                        Style style) {
480   StringRef p(path.begin(), path.size());
481   SmallString<32> ext_storage;
482   StringRef ext = extension.toStringRef(ext_storage);
483 
484   // Erase existing extension.
485   size_t pos = p.find_last_of('.');
486   if (pos != StringRef::npos && pos >= filename_pos(p, style))
487     path.set_size(pos);
488 
489   // Append '.' if needed.
490   if (ext.size() > 0 && ext[0] != '.')
491     path.push_back('.');
492 
493   // Append extension.
494   path.append(ext.begin(), ext.end());
495 }
496 
497 static bool starts_with(StringRef Path, StringRef Prefix,
498                         Style style = Style::native) {
499   // Windows prefix matching : case and separator insensitive
500   if (is_style_windows(style)) {
501     if (Path.size() < Prefix.size())
502       return false;
503     for (size_t I = 0, E = Prefix.size(); I != E; ++I) {
504       bool SepPath = is_separator(Path[I], style);
505       bool SepPrefix = is_separator(Prefix[I], style);
506       if (SepPath != SepPrefix)
507         return false;
508       if (!SepPath && toLower(Path[I]) != toLower(Prefix[I]))
509         return false;
510     }
511     return true;
512   }
513   return Path.startswith(Prefix);
514 }
515 
516 bool replace_path_prefix(SmallVectorImpl<char> &Path, StringRef OldPrefix,
517                          StringRef NewPrefix, Style style) {
518   if (OldPrefix.empty() && NewPrefix.empty())
519     return false;
520 
521   StringRef OrigPath(Path.begin(), Path.size());
522   if (!starts_with(OrigPath, OldPrefix, style))
523     return false;
524 
525   // If prefixes have the same size we can simply copy the new one over.
526   if (OldPrefix.size() == NewPrefix.size()) {
527     llvm::copy(NewPrefix, Path.begin());
528     return true;
529   }
530 
531   StringRef RelPath = OrigPath.substr(OldPrefix.size());
532   SmallString<256> NewPath;
533   (Twine(NewPrefix) + RelPath).toVector(NewPath);
534   Path.swap(NewPath);
535   return true;
536 }
537 
538 void native(const Twine &path, SmallVectorImpl<char> &result, Style style) {
539   assert((!path.isSingleStringRef() ||
540           path.getSingleStringRef().data() != result.data()) &&
541          "path and result are not allowed to overlap!");
542   // Clear result.
543   result.clear();
544   path.toVector(result);
545   native(result, style);
546 }
547 
548 void native(SmallVectorImpl<char> &Path, Style style) {
549   if (Path.empty())
550     return;
551   if (is_style_windows(style)) {
552     for (char &Ch : Path)
553       if (is_separator(Ch, style))
554         Ch = preferred_separator(style);
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     std::replace(Path.begin(), Path.end(), '\\', '/');
563   }
564 }
565 
566 std::string convert_to_slash(StringRef path, Style style) {
567   if (is_style_posix(style))
568     return std::string(path);
569 
570   std::string s = path.str();
571   std::replace(s.begin(), s.end(), '\\', '/');
572   return s;
573 }
574 
575 StringRef filename(StringRef path, Style style) { return *rbegin(path, style); }
576 
577 StringRef stem(StringRef path, Style style) {
578   StringRef fname = filename(path, style);
579   size_t pos = fname.find_last_of('.');
580   if (pos == StringRef::npos)
581     return fname;
582   if ((fname.size() == 1 && fname == ".") ||
583       (fname.size() == 2 && fname == ".."))
584     return fname;
585   return fname.substr(0, pos);
586 }
587 
588 StringRef extension(StringRef path, Style style) {
589   StringRef fname = filename(path, style);
590   size_t pos = fname.find_last_of('.');
591   if (pos == StringRef::npos)
592     return StringRef();
593   if ((fname.size() == 1 && fname == ".") ||
594       (fname.size() == 2 && fname == ".."))
595     return StringRef();
596   return fname.substr(pos);
597 }
598 
599 bool is_separator(char value, Style style) {
600   if (value == '/')
601     return true;
602   if (is_style_windows(style))
603     return value == '\\';
604   return false;
605 }
606 
607 StringRef get_separator(Style style) {
608   if (real_style(style) == Style::windows)
609     return "\\";
610   return "/";
611 }
612 
613 bool has_root_name(const Twine &path, Style style) {
614   SmallString<128> path_storage;
615   StringRef p = path.toStringRef(path_storage);
616 
617   return !root_name(p, style).empty();
618 }
619 
620 bool has_root_directory(const Twine &path, Style style) {
621   SmallString<128> path_storage;
622   StringRef p = path.toStringRef(path_storage);
623 
624   return !root_directory(p, style).empty();
625 }
626 
627 bool has_root_path(const Twine &path, Style style) {
628   SmallString<128> path_storage;
629   StringRef p = path.toStringRef(path_storage);
630 
631   return !root_path(p, style).empty();
632 }
633 
634 bool has_relative_path(const Twine &path, Style style) {
635   SmallString<128> path_storage;
636   StringRef p = path.toStringRef(path_storage);
637 
638   return !relative_path(p, style).empty();
639 }
640 
641 bool has_filename(const Twine &path, Style style) {
642   SmallString<128> path_storage;
643   StringRef p = path.toStringRef(path_storage);
644 
645   return !filename(p, style).empty();
646 }
647 
648 bool has_parent_path(const Twine &path, Style style) {
649   SmallString<128> path_storage;
650   StringRef p = path.toStringRef(path_storage);
651 
652   return !parent_path(p, style).empty();
653 }
654 
655 bool has_stem(const Twine &path, Style style) {
656   SmallString<128> path_storage;
657   StringRef p = path.toStringRef(path_storage);
658 
659   return !stem(p, style).empty();
660 }
661 
662 bool has_extension(const Twine &path, Style style) {
663   SmallString<128> path_storage;
664   StringRef p = path.toStringRef(path_storage);
665 
666   return !extension(p, style).empty();
667 }
668 
669 bool is_absolute(const Twine &path, Style style) {
670   SmallString<128> path_storage;
671   StringRef p = path.toStringRef(path_storage);
672 
673   bool rootDir = has_root_directory(p, style);
674   bool rootName = is_style_posix(style) || has_root_name(p, style);
675 
676   return rootDir && rootName;
677 }
678 
679 bool is_absolute_gnu(const Twine &path, Style style) {
680   SmallString<128> path_storage;
681   StringRef p = path.toStringRef(path_storage);
682 
683   // Handle '/' which is absolute for both Windows and POSIX systems.
684   // Handle '\\' on Windows.
685   if (!p.empty() && is_separator(p.front(), style))
686     return true;
687 
688   if (is_style_windows(style)) {
689     // Handle drive letter pattern (a character followed by ':') on Windows.
690     if (p.size() >= 2 && (p[0] && p[1] == ':'))
691       return true;
692   }
693 
694   return false;
695 }
696 
697 bool is_relative(const Twine &path, Style style) {
698   return !is_absolute(path, style);
699 }
700 
701 StringRef remove_leading_dotslash(StringRef Path, Style style) {
702   // Remove leading "./" (or ".//" or "././" etc.)
703   while (Path.size() > 2 && Path[0] == '.' && is_separator(Path[1], style)) {
704     Path = Path.substr(2);
705     while (Path.size() > 0 && is_separator(Path[0], style))
706       Path = Path.substr(1);
707   }
708   return Path;
709 }
710 
711 // Remove path traversal components ("." and "..") when possible, and
712 // canonicalize slashes.
713 bool remove_dots(SmallVectorImpl<char> &the_path, bool remove_dot_dot,
714                  Style style) {
715   style = real_style(style);
716   StringRef remaining(the_path.data(), the_path.size());
717   bool needs_change = false;
718   SmallVector<StringRef, 16> components;
719 
720   // Consume the root path, if present.
721   StringRef root = path::root_path(remaining, style);
722   bool absolute = !root.empty();
723   if (absolute)
724     remaining = remaining.drop_front(root.size());
725 
726   // Loop over path components manually. This makes it easier to detect
727   // non-preferred slashes and double separators that must be canonicalized.
728   while (!remaining.empty()) {
729     size_t next_slash = remaining.find_first_of(separators(style));
730     if (next_slash == StringRef::npos)
731       next_slash = remaining.size();
732     StringRef component = remaining.take_front(next_slash);
733     remaining = remaining.drop_front(next_slash);
734 
735     // Eat the slash, and check if it is the preferred separator.
736     if (!remaining.empty()) {
737       needs_change |= remaining.front() != preferred_separator(style);
738       remaining = remaining.drop_front();
739       // The path needs to be rewritten if it has a trailing slash.
740       // FIXME: This is emergent behavior that could be removed.
741       needs_change |= remaining.empty();
742     }
743 
744     // Check for path traversal components or double separators.
745     if (component.empty() || component == ".") {
746       needs_change = true;
747     } else if (remove_dot_dot && component == "..") {
748       needs_change = true;
749       // Do not allow ".." to remove the root component. If this is the
750       // beginning of a relative path, keep the ".." component.
751       if (!components.empty() && components.back() != "..") {
752         components.pop_back();
753       } else if (!absolute) {
754         components.push_back(component);
755       }
756     } else {
757       components.push_back(component);
758     }
759   }
760 
761   // Avoid rewriting the path unless we have to.
762   if (!needs_change)
763     return false;
764 
765   SmallString<256> buffer = root;
766   if (!components.empty()) {
767     buffer += components[0];
768     for (StringRef C : makeArrayRef(components).drop_front()) {
769       buffer += preferred_separator(style);
770       buffer += C;
771     }
772   }
773   the_path.swap(buffer);
774   return true;
775 }
776 
777 } // end namespace path
778 
779 namespace fs {
780 
781 std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
782   file_status Status;
783   std::error_code EC = status(Path, Status);
784   if (EC)
785     return EC;
786   Result = Status.getUniqueID();
787   return std::error_code();
788 }
789 
790 void createUniquePath(const Twine &Model, SmallVectorImpl<char> &ResultPath,
791                       bool MakeAbsolute) {
792   SmallString<128> ModelStorage;
793   Model.toVector(ModelStorage);
794 
795   if (MakeAbsolute) {
796     // Make model absolute by prepending a temp directory if it's not already.
797     if (!sys::path::is_absolute(Twine(ModelStorage))) {
798       SmallString<128> TDir;
799       sys::path::system_temp_directory(true, TDir);
800       sys::path::append(TDir, Twine(ModelStorage));
801       ModelStorage.swap(TDir);
802     }
803   }
804 
805   ResultPath = ModelStorage;
806   ResultPath.push_back(0);
807   ResultPath.pop_back();
808 
809   // Replace '%' with random chars.
810   for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
811     if (ModelStorage[i] == '%')
812       ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
813   }
814 }
815 
816 std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
817                                  SmallVectorImpl<char> &ResultPath,
818                                  OpenFlags Flags, unsigned Mode) {
819   return createUniqueEntity(Model, ResultFd, ResultPath, false, FS_File, Flags,
820                             Mode);
821 }
822 
823 std::error_code createUniqueFile(const Twine &Model,
824                                  SmallVectorImpl<char> &ResultPath,
825                                  unsigned Mode) {
826   int FD;
827   auto EC = createUniqueFile(Model, FD, ResultPath, OF_None, Mode);
828   if (EC)
829     return EC;
830   // FD is only needed to avoid race conditions. Close it right away.
831   close(FD);
832   return EC;
833 }
834 
835 static std::error_code
836 createTemporaryFile(const Twine &Model, int &ResultFD,
837                     llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type,
838                     sys::fs::OpenFlags Flags = sys::fs::OF_None) {
839   SmallString<128> Storage;
840   StringRef P = Model.toNullTerminatedStringRef(Storage);
841   assert(P.find_first_of(separators(Style::native)) == StringRef::npos &&
842          "Model must be a simple filename.");
843   // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
844   return createUniqueEntity(P.begin(), ResultFD, ResultPath, true, Type, Flags,
845                             owner_read | owner_write);
846 }
847 
848 static std::error_code
849 createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
850                     llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type,
851                     sys::fs::OpenFlags Flags = sys::fs::OF_None) {
852   const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
853   return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
854                              Type, Flags);
855 }
856 
857 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
858                                     int &ResultFD,
859                                     SmallVectorImpl<char> &ResultPath,
860                                     sys::fs::OpenFlags Flags) {
861   return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File,
862                              Flags);
863 }
864 
865 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
866                                     SmallVectorImpl<char> &ResultPath,
867                                     sys::fs::OpenFlags Flags) {
868   int FD;
869   auto EC = createTemporaryFile(Prefix, Suffix, FD, ResultPath, Flags);
870   if (EC)
871     return EC;
872   // FD is only needed to avoid race conditions. Close it right away.
873   close(FD);
874   return EC;
875 }
876 
877 // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
878 // for consistency. We should try using mkdtemp.
879 std::error_code createUniqueDirectory(const Twine &Prefix,
880                                       SmallVectorImpl<char> &ResultPath) {
881   int Dummy;
882   return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath, true,
883                             FS_Dir);
884 }
885 
886 std::error_code
887 getPotentiallyUniqueFileName(const Twine &Model,
888                              SmallVectorImpl<char> &ResultPath) {
889   int Dummy;
890   return createUniqueEntity(Model, Dummy, ResultPath, false, FS_Name);
891 }
892 
893 std::error_code
894 getPotentiallyUniqueTempFileName(const Twine &Prefix, StringRef Suffix,
895                                  SmallVectorImpl<char> &ResultPath) {
896   int Dummy;
897   return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
898 }
899 
900 void make_absolute(const Twine &current_directory,
901                    SmallVectorImpl<char> &path) {
902   StringRef p(path.data(), path.size());
903 
904   bool rootDirectory = path::has_root_directory(p);
905   bool rootName = path::has_root_name(p);
906 
907   // Already absolute.
908   if ((rootName || is_style_posix(Style::native)) && rootDirectory)
909     return;
910 
911   // All of the following conditions will need the current directory.
912   SmallString<128> current_dir;
913   current_directory.toVector(current_dir);
914 
915   // Relative path. Prepend the current directory.
916   if (!rootName && !rootDirectory) {
917     // Append path to the current directory.
918     path::append(current_dir, p);
919     // Set path to the result.
920     path.swap(current_dir);
921     return;
922   }
923 
924   if (!rootName && rootDirectory) {
925     StringRef cdrn = path::root_name(current_dir);
926     SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
927     path::append(curDirRootName, p);
928     // Set path to the result.
929     path.swap(curDirRootName);
930     return;
931   }
932 
933   if (rootName && !rootDirectory) {
934     StringRef pRootName      = path::root_name(p);
935     StringRef bRootDirectory = path::root_directory(current_dir);
936     StringRef bRelativePath  = path::relative_path(current_dir);
937     StringRef pRelativePath  = path::relative_path(p);
938 
939     SmallString<128> res;
940     path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
941     path.swap(res);
942     return;
943   }
944 
945   llvm_unreachable("All rootName and rootDirectory combinations should have "
946                    "occurred above!");
947 }
948 
949 std::error_code make_absolute(SmallVectorImpl<char> &path) {
950   if (path::is_absolute(path))
951     return {};
952 
953   SmallString<128> current_dir;
954   if (std::error_code ec = current_path(current_dir))
955     return ec;
956 
957   make_absolute(current_dir, path);
958   return {};
959 }
960 
961 std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
962                                    perms Perms) {
963   SmallString<128> PathStorage;
964   StringRef P = Path.toStringRef(PathStorage);
965 
966   // Be optimistic and try to create the directory
967   std::error_code EC = create_directory(P, IgnoreExisting, Perms);
968   // If we succeeded, or had any error other than the parent not existing, just
969   // return it.
970   if (EC != errc::no_such_file_or_directory)
971     return EC;
972 
973   // We failed because of a no_such_file_or_directory, try to create the
974   // parent.
975   StringRef Parent = path::parent_path(P);
976   if (Parent.empty())
977     return EC;
978 
979   if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
980       return EC;
981 
982   return create_directory(P, IgnoreExisting, Perms);
983 }
984 
985 static std::error_code copy_file_internal(int ReadFD, int WriteFD) {
986   const size_t BufSize = 4096;
987   char *Buf = new char[BufSize];
988   int BytesRead = 0, BytesWritten = 0;
989   for (;;) {
990     BytesRead = read(ReadFD, Buf, BufSize);
991     if (BytesRead <= 0)
992       break;
993     while (BytesRead) {
994       BytesWritten = write(WriteFD, Buf, BytesRead);
995       if (BytesWritten < 0)
996         break;
997       BytesRead -= BytesWritten;
998     }
999     if (BytesWritten < 0)
1000       break;
1001   }
1002   delete[] Buf;
1003 
1004   if (BytesRead < 0 || BytesWritten < 0)
1005     return std::error_code(errno, std::generic_category());
1006   return std::error_code();
1007 }
1008 
1009 #ifndef __APPLE__
1010 std::error_code copy_file(const Twine &From, const Twine &To) {
1011   int ReadFD, WriteFD;
1012   if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
1013     return EC;
1014   if (std::error_code EC =
1015           openFileForWrite(To, WriteFD, CD_CreateAlways, OF_None)) {
1016     close(ReadFD);
1017     return EC;
1018   }
1019 
1020   std::error_code EC = copy_file_internal(ReadFD, WriteFD);
1021 
1022   close(ReadFD);
1023   close(WriteFD);
1024 
1025   return EC;
1026 }
1027 #endif
1028 
1029 std::error_code copy_file(const Twine &From, int ToFD) {
1030   int ReadFD;
1031   if (std::error_code EC = openFileForRead(From, ReadFD, OF_None))
1032     return EC;
1033 
1034   std::error_code EC = copy_file_internal(ReadFD, ToFD);
1035 
1036   close(ReadFD);
1037 
1038   return EC;
1039 }
1040 
1041 ErrorOr<MD5::MD5Result> md5_contents(int FD) {
1042   MD5 Hash;
1043 
1044   constexpr size_t BufSize = 4096;
1045   std::vector<uint8_t> Buf(BufSize);
1046   int BytesRead = 0;
1047   for (;;) {
1048     BytesRead = read(FD, Buf.data(), BufSize);
1049     if (BytesRead <= 0)
1050       break;
1051     Hash.update(makeArrayRef(Buf.data(), BytesRead));
1052   }
1053 
1054   if (BytesRead < 0)
1055     return std::error_code(errno, std::generic_category());
1056   MD5::MD5Result Result;
1057   Hash.final(Result);
1058   return Result;
1059 }
1060 
1061 ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path) {
1062   int FD;
1063   if (auto EC = openFileForRead(Path, FD, OF_None))
1064     return EC;
1065 
1066   auto Result = md5_contents(FD);
1067   close(FD);
1068   return Result;
1069 }
1070 
1071 bool exists(const basic_file_status &status) {
1072   return status_known(status) && status.type() != file_type::file_not_found;
1073 }
1074 
1075 bool status_known(const basic_file_status &s) {
1076   return s.type() != file_type::status_error;
1077 }
1078 
1079 file_type get_file_type(const Twine &Path, bool Follow) {
1080   file_status st;
1081   if (status(Path, st, Follow))
1082     return file_type::status_error;
1083   return st.type();
1084 }
1085 
1086 bool is_directory(const basic_file_status &status) {
1087   return status.type() == file_type::directory_file;
1088 }
1089 
1090 std::error_code is_directory(const Twine &path, bool &result) {
1091   file_status st;
1092   if (std::error_code ec = status(path, st))
1093     return ec;
1094   result = is_directory(st);
1095   return std::error_code();
1096 }
1097 
1098 bool is_regular_file(const basic_file_status &status) {
1099   return status.type() == file_type::regular_file;
1100 }
1101 
1102 std::error_code is_regular_file(const Twine &path, bool &result) {
1103   file_status st;
1104   if (std::error_code ec = status(path, st))
1105     return ec;
1106   result = is_regular_file(st);
1107   return std::error_code();
1108 }
1109 
1110 bool is_symlink_file(const basic_file_status &status) {
1111   return status.type() == file_type::symlink_file;
1112 }
1113 
1114 std::error_code is_symlink_file(const Twine &path, bool &result) {
1115   file_status st;
1116   if (std::error_code ec = status(path, st, false))
1117     return ec;
1118   result = is_symlink_file(st);
1119   return std::error_code();
1120 }
1121 
1122 bool is_other(const basic_file_status &status) {
1123   return exists(status) &&
1124          !is_regular_file(status) &&
1125          !is_directory(status);
1126 }
1127 
1128 std::error_code is_other(const Twine &Path, bool &Result) {
1129   file_status FileStatus;
1130   if (std::error_code EC = status(Path, FileStatus))
1131     return EC;
1132   Result = is_other(FileStatus);
1133   return std::error_code();
1134 }
1135 
1136 void directory_entry::replace_filename(const Twine &Filename, file_type Type,
1137                                        basic_file_status Status) {
1138   SmallString<128> PathStr = path::parent_path(Path);
1139   path::append(PathStr, Filename);
1140   this->Path = std::string(PathStr.str());
1141   this->Type = Type;
1142   this->Status = Status;
1143 }
1144 
1145 ErrorOr<perms> getPermissions(const Twine &Path) {
1146   file_status Status;
1147   if (std::error_code EC = status(Path, Status))
1148     return EC;
1149 
1150   return Status.permissions();
1151 }
1152 
1153 size_t mapped_file_region::size() const {
1154   assert(Mapping && "Mapping failed but used anyway!");
1155   return Size;
1156 }
1157 
1158 char *mapped_file_region::data() const {
1159   assert(Mapping && "Mapping failed but used anyway!");
1160   return reinterpret_cast<char *>(Mapping);
1161 }
1162 
1163 const char *mapped_file_region::const_data() const {
1164   assert(Mapping && "Mapping failed but used anyway!");
1165   return reinterpret_cast<const char *>(Mapping);
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 #ifdef _WIN32
1192   RemoveOnClose = Other.RemoveOnClose;
1193   Other.RemoveOnClose = false;
1194 #endif
1195   return *this;
1196 }
1197 
1198 TempFile::~TempFile() { assert(Done); }
1199 
1200 Error TempFile::discard() {
1201   Done = true;
1202   if (FD != -1 && close(FD) == -1) {
1203     std::error_code EC = std::error_code(errno, std::generic_category());
1204     return errorCodeToError(EC);
1205   }
1206   FD = -1;
1207 
1208 #ifdef _WIN32
1209   // On Windows, closing will remove the file, if we set the delete
1210   // disposition. If not, remove it manually.
1211   bool Remove = RemoveOnClose;
1212 #else
1213   // Always try to remove the file.
1214   bool Remove = true;
1215 #endif
1216   std::error_code RemoveEC;
1217   if (Remove && !TmpName.empty()) {
1218     RemoveEC = fs::remove(TmpName);
1219     sys::DontRemoveFileOnSignal(TmpName);
1220     if (!RemoveEC)
1221       TmpName = "";
1222   } else {
1223     TmpName = "";
1224   }
1225   return errorCodeToError(RemoveEC);
1226 }
1227 
1228 Error TempFile::keep(const Twine &Name) {
1229   assert(!Done);
1230   Done = true;
1231   // Always try to close and rename.
1232 #ifdef _WIN32
1233   // If we can't cancel the delete don't rename.
1234   auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1235   std::error_code RenameEC = setDeleteDisposition(H, false);
1236   bool ShouldDelete = false;
1237   if (!RenameEC) {
1238     RenameEC = rename_handle(H, Name);
1239     // If rename failed because it's cross-device, copy instead
1240     if (RenameEC ==
1241       std::error_code(ERROR_NOT_SAME_DEVICE, std::system_category())) {
1242       RenameEC = copy_file(TmpName, Name);
1243       ShouldDelete = true;
1244     }
1245   }
1246 
1247   // If we can't rename or copy, discard the temporary file.
1248   if (RenameEC)
1249     ShouldDelete = true;
1250   if (ShouldDelete) {
1251     if (!RemoveOnClose)
1252       setDeleteDisposition(H, true);
1253     else
1254       remove(TmpName);
1255   }
1256 #else
1257   std::error_code RenameEC = fs::rename(TmpName, Name);
1258   if (RenameEC) {
1259     // If we can't rename, try to copy to work around cross-device link issues.
1260     RenameEC = sys::fs::copy_file(TmpName, Name);
1261     // If we can't rename or copy, discard the temporary file.
1262     if (RenameEC)
1263       remove(TmpName);
1264   }
1265 #endif
1266   sys::DontRemoveFileOnSignal(TmpName);
1267 
1268   if (!RenameEC)
1269     TmpName = "";
1270 
1271   if (close(FD) == -1) {
1272     std::error_code EC(errno, std::generic_category());
1273     return errorCodeToError(EC);
1274   }
1275   FD = -1;
1276 
1277   return errorCodeToError(RenameEC);
1278 }
1279 
1280 Error TempFile::keep() {
1281   assert(!Done);
1282   Done = true;
1283 
1284 #ifdef _WIN32
1285   auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1286   if (std::error_code EC = setDeleteDisposition(H, false))
1287     return errorCodeToError(EC);
1288 #endif
1289   sys::DontRemoveFileOnSignal(TmpName);
1290 
1291   TmpName = "";
1292 
1293   if (close(FD) == -1) {
1294     std::error_code EC(errno, std::generic_category());
1295     return errorCodeToError(EC);
1296   }
1297   FD = -1;
1298 
1299   return Error::success();
1300 }
1301 
1302 Expected<TempFile> TempFile::create(const Twine &Model, unsigned Mode,
1303                                     OpenFlags ExtraFlags) {
1304   int FD;
1305   SmallString<128> ResultPath;
1306   if (std::error_code EC =
1307           createUniqueFile(Model, FD, ResultPath, OF_Delete | ExtraFlags, Mode))
1308     return errorCodeToError(EC);
1309 
1310   TempFile Ret(ResultPath, FD);
1311 #ifdef _WIN32
1312   auto H = reinterpret_cast<HANDLE>(_get_osfhandle(FD));
1313   bool SetSignalHandler = false;
1314   if (std::error_code EC = setDeleteDisposition(H, true)) {
1315     Ret.RemoveOnClose = true;
1316     SetSignalHandler = true;
1317   }
1318 #else
1319   bool SetSignalHandler = true;
1320 #endif
1321   if (SetSignalHandler && sys::RemoveFileOnSignal(ResultPath)) {
1322     // Make sure we delete the file when RemoveFileOnSignal fails.
1323     consumeError(Ret.discard());
1324     std::error_code EC(errc::operation_not_permitted);
1325     return errorCodeToError(EC);
1326   }
1327   return std::move(Ret);
1328 }
1329 } // namespace fs
1330 
1331 } // namespace sys
1332 } // namespace llvm
1333