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