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