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