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