]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Support/Path.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304149, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Support / Path.cpp
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/COFF.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/MachO.h"
22 #include "llvm/Support/Process.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 LLVM_ON_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 createUniqueEntity(const Twine &Model, int &ResultFD,
165                                           SmallVectorImpl<char> &ResultPath,
166                                           bool MakeAbsolute, unsigned Mode,
167                                           FSEntity Type) {
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                                       sys::fs::F_RW | 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     bool component_has_sep =
445         !component.empty() && is_separator(component[0], style);
446     bool is_root_name = has_root_name(component, style);
447
448     if (path_has_sep) {
449       // Strip separators from beginning of component.
450       size_t loc = component.find_first_not_of(separators(style));
451       StringRef c = component.substr(loc);
452
453       // Append it.
454       path.append(c.begin(), c.end());
455       continue;
456     }
457
458     if (!component_has_sep && !(path.empty() || is_root_name)) {
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) {
756   return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
757 }
758
759 std::error_code createUniqueFile(const Twine &Model,
760                                  SmallVectorImpl<char> &ResultPath) {
761   int Dummy;
762   return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
763 }
764
765 static std::error_code
766 createTemporaryFile(const Twine &Model, int &ResultFD,
767                     llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
768   SmallString<128> Storage;
769   StringRef P = Model.toNullTerminatedStringRef(Storage);
770   assert(P.find_first_of(separators(Style::native)) == StringRef::npos &&
771          "Model must be a simple filename.");
772   // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
773   return createUniqueEntity(P.begin(), ResultFD, ResultPath,
774                             true, owner_read | owner_write, Type);
775 }
776
777 static std::error_code
778 createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
779                     llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
780   const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
781   return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
782                              Type);
783 }
784
785 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
786                                     int &ResultFD,
787                                     SmallVectorImpl<char> &ResultPath) {
788   return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
789 }
790
791 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
792                                     SmallVectorImpl<char> &ResultPath) {
793   int Dummy;
794   return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
795 }
796
797
798 // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
799 // for consistency. We should try using mkdtemp.
800 std::error_code createUniqueDirectory(const Twine &Prefix,
801                                       SmallVectorImpl<char> &ResultPath) {
802   int Dummy;
803   return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
804                             true, 0, FS_Dir);
805 }
806
807 static std::error_code make_absolute(const Twine &current_directory,
808                                      SmallVectorImpl<char> &path,
809                                      bool use_current_directory) {
810   StringRef p(path.data(), path.size());
811
812   bool rootDirectory = path::has_root_directory(p);
813   bool rootName =
814       (real_style(Style::native) != Style::windows) || path::has_root_name(p);
815
816   // Already absolute.
817   if (rootName && rootDirectory)
818     return std::error_code();
819
820   // All of the following conditions will need the current directory.
821   SmallString<128> current_dir;
822   if (use_current_directory)
823     current_directory.toVector(current_dir);
824   else if (std::error_code ec = current_path(current_dir))
825     return ec;
826
827   // Relative path. Prepend the current directory.
828   if (!rootName && !rootDirectory) {
829     // Append path to the current directory.
830     path::append(current_dir, p);
831     // Set path to the result.
832     path.swap(current_dir);
833     return std::error_code();
834   }
835
836   if (!rootName && rootDirectory) {
837     StringRef cdrn = path::root_name(current_dir);
838     SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
839     path::append(curDirRootName, p);
840     // Set path to the result.
841     path.swap(curDirRootName);
842     return std::error_code();
843   }
844
845   if (rootName && !rootDirectory) {
846     StringRef pRootName      = path::root_name(p);
847     StringRef bRootDirectory = path::root_directory(current_dir);
848     StringRef bRelativePath  = path::relative_path(current_dir);
849     StringRef pRelativePath  = path::relative_path(p);
850
851     SmallString<128> res;
852     path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
853     path.swap(res);
854     return std::error_code();
855   }
856
857   llvm_unreachable("All rootName and rootDirectory combinations should have "
858                    "occurred above!");
859 }
860
861 std::error_code make_absolute(const Twine &current_directory,
862                               SmallVectorImpl<char> &path) {
863   return make_absolute(current_directory, path, true);
864 }
865
866 std::error_code make_absolute(SmallVectorImpl<char> &path) {
867   return make_absolute(Twine(), path, false);
868 }
869
870 std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
871                                    perms Perms) {
872   SmallString<128> PathStorage;
873   StringRef P = Path.toStringRef(PathStorage);
874
875   // Be optimistic and try to create the directory
876   std::error_code EC = create_directory(P, IgnoreExisting, Perms);
877   // If we succeeded, or had any error other than the parent not existing, just
878   // return it.
879   if (EC != errc::no_such_file_or_directory)
880     return EC;
881
882   // We failed because of a no_such_file_or_directory, try to create the
883   // parent.
884   StringRef Parent = path::parent_path(P);
885   if (Parent.empty())
886     return EC;
887
888   if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
889       return EC;
890
891   return create_directory(P, IgnoreExisting, Perms);
892 }
893
894 std::error_code copy_file(const Twine &From, const Twine &To) {
895   int ReadFD, WriteFD;
896   if (std::error_code EC = openFileForRead(From, ReadFD))
897     return EC;
898   if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
899     close(ReadFD);
900     return EC;
901   }
902
903   const size_t BufSize = 4096;
904   char *Buf = new char[BufSize];
905   int BytesRead = 0, BytesWritten = 0;
906   for (;;) {
907     BytesRead = read(ReadFD, Buf, BufSize);
908     if (BytesRead <= 0)
909       break;
910     while (BytesRead) {
911       BytesWritten = write(WriteFD, Buf, BytesRead);
912       if (BytesWritten < 0)
913         break;
914       BytesRead -= BytesWritten;
915     }
916     if (BytesWritten < 0)
917       break;
918   }
919   close(ReadFD);
920   close(WriteFD);
921   delete[] Buf;
922
923   if (BytesRead < 0 || BytesWritten < 0)
924     return std::error_code(errno, std::generic_category());
925   return std::error_code();
926 }
927
928 ErrorOr<MD5::MD5Result> md5_contents(int FD) {
929   MD5 Hash;
930
931   constexpr size_t BufSize = 4096;
932   std::vector<uint8_t> Buf(BufSize);
933   int BytesRead = 0;
934   for (;;) {
935     BytesRead = read(FD, Buf.data(), BufSize);
936     if (BytesRead <= 0)
937       break;
938     Hash.update(makeArrayRef(Buf.data(), BytesRead));
939   }
940
941   if (BytesRead < 0)
942     return std::error_code(errno, std::generic_category());
943   MD5::MD5Result Result;
944   Hash.final(Result);
945   return Result;
946 }
947
948 ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path) {
949   int FD;
950   if (auto EC = openFileForRead(Path, FD))
951     return EC;
952
953   auto Result = md5_contents(FD);
954   close(FD);
955   return Result;
956 }
957
958 bool exists(file_status status) {
959   return status_known(status) && status.type() != file_type::file_not_found;
960 }
961
962 bool status_known(file_status s) {
963   return s.type() != file_type::status_error;
964 }
965
966 file_type get_file_type(const Twine &Path, bool Follow) {
967   file_status st;
968   if (status(Path, st, Follow))
969     return file_type::status_error;
970   return st.type();
971 }
972
973 bool is_directory(file_status status) {
974   return status.type() == file_type::directory_file;
975 }
976
977 std::error_code is_directory(const Twine &path, bool &result) {
978   file_status st;
979   if (std::error_code ec = status(path, st))
980     return ec;
981   result = is_directory(st);
982   return std::error_code();
983 }
984
985 bool is_regular_file(file_status status) {
986   return status.type() == file_type::regular_file;
987 }
988
989 std::error_code is_regular_file(const Twine &path, bool &result) {
990   file_status st;
991   if (std::error_code ec = status(path, st))
992     return ec;
993   result = is_regular_file(st);
994   return std::error_code();
995 }
996
997 bool is_symlink_file(file_status status) {
998   return status.type() == file_type::symlink_file;
999 }
1000
1001 std::error_code is_symlink_file(const Twine &path, bool &result) {
1002   file_status st;
1003   if (std::error_code ec = status(path, st, false))
1004     return ec;
1005   result = is_symlink_file(st);
1006   return std::error_code();
1007 }
1008
1009 bool is_other(file_status status) {
1010   return exists(status) &&
1011          !is_regular_file(status) &&
1012          !is_directory(status);
1013 }
1014
1015 std::error_code is_other(const Twine &Path, bool &Result) {
1016   file_status FileStatus;
1017   if (std::error_code EC = status(Path, FileStatus))
1018     return EC;
1019   Result = is_other(FileStatus);
1020   return std::error_code();
1021 }
1022
1023 void directory_entry::replace_filename(const Twine &filename, file_status st) {
1024   SmallString<128> path = path::parent_path(Path);
1025   path::append(path, filename);
1026   Path = path.str();
1027   Status = st;
1028 }
1029
1030 template <size_t N>
1031 static bool startswith(StringRef Magic, const char (&S)[N]) {
1032   return Magic.startswith(StringRef(S, N - 1));
1033 }
1034
1035 /// @brief Identify the magic in magic.
1036 file_magic identify_magic(StringRef Magic) {
1037   if (Magic.size() < 4)
1038     return file_magic::unknown;
1039   switch ((unsigned char)Magic[0]) {
1040     case 0x00: {
1041       // COFF bigobj, CL.exe's LTO object file, or short import library file
1042       if (startswith(Magic, "\0\0\xFF\xFF")) {
1043         size_t MinSize = offsetof(COFF::BigObjHeader, UUID) + sizeof(COFF::BigObjMagic);
1044         if (Magic.size() < MinSize)
1045           return file_magic::coff_import_library;
1046
1047         const char *Start = Magic.data() + offsetof(COFF::BigObjHeader, UUID);
1048         if (memcmp(Start, COFF::BigObjMagic, sizeof(COFF::BigObjMagic)) == 0)
1049           return file_magic::coff_object;
1050         if (memcmp(Start, COFF::ClGlObjMagic, sizeof(COFF::BigObjMagic)) == 0)
1051           return file_magic::coff_cl_gl_object;
1052         return file_magic::coff_import_library;
1053       }
1054       // Windows resource file
1055       if (startswith(Magic, "\0\0\0\0\x20\0\0\0\xFF"))
1056         return file_magic::windows_resource;
1057       // 0x0000 = COFF unknown machine type
1058       if (Magic[1] == 0)
1059         return file_magic::coff_object;
1060       if (startswith(Magic, "\0asm"))
1061         return file_magic::wasm_object;
1062       break;
1063     }
1064     case 0xDE:  // 0x0B17C0DE = BC wraper
1065       if (startswith(Magic, "\xDE\xC0\x17\x0B"))
1066         return file_magic::bitcode;
1067       break;
1068     case 'B':
1069       if (startswith(Magic, "BC\xC0\xDE"))
1070         return file_magic::bitcode;
1071       break;
1072     case '!':
1073       if (startswith(Magic, "!<arch>\n") || startswith(Magic, "!<thin>\n"))
1074         return file_magic::archive;
1075       break;
1076
1077     case '\177':
1078       if (startswith(Magic, "\177ELF") && Magic.size() >= 18) {
1079         bool Data2MSB = Magic[5] == 2;
1080         unsigned high = Data2MSB ? 16 : 17;
1081         unsigned low  = Data2MSB ? 17 : 16;
1082         if (Magic[high] == 0) {
1083           switch (Magic[low]) {
1084             default: return file_magic::elf;
1085             case 1: return file_magic::elf_relocatable;
1086             case 2: return file_magic::elf_executable;
1087             case 3: return file_magic::elf_shared_object;
1088             case 4: return file_magic::elf_core;
1089           }
1090         }
1091         // It's still some type of ELF file.
1092         return file_magic::elf;
1093       }
1094       break;
1095
1096     case 0xCA:
1097       if (startswith(Magic, "\xCA\xFE\xBA\xBE") ||
1098           startswith(Magic, "\xCA\xFE\xBA\xBF")) {
1099         // This is complicated by an overlap with Java class files.
1100         // See the Mach-O section in /usr/share/file/magic for details.
1101         if (Magic.size() >= 8 && Magic[7] < 43)
1102           return file_magic::macho_universal_binary;
1103       }
1104       break;
1105
1106       // The two magic numbers for mach-o are:
1107       // 0xfeedface - 32-bit mach-o
1108       // 0xfeedfacf - 64-bit mach-o
1109     case 0xFE:
1110     case 0xCE:
1111     case 0xCF: {
1112       uint16_t type = 0;
1113       if (startswith(Magic, "\xFE\xED\xFA\xCE") ||
1114           startswith(Magic, "\xFE\xED\xFA\xCF")) {
1115         /* Native endian */
1116         size_t MinSize;
1117         if (Magic[3] == char(0xCE))
1118           MinSize = sizeof(MachO::mach_header);
1119         else
1120           MinSize = sizeof(MachO::mach_header_64);
1121         if (Magic.size() >= MinSize)
1122           type = Magic[12] << 24 | Magic[13] << 12 | Magic[14] << 8 | Magic[15];
1123       } else if (startswith(Magic, "\xCE\xFA\xED\xFE") ||
1124                  startswith(Magic, "\xCF\xFA\xED\xFE")) {
1125         /* Reverse endian */
1126         size_t MinSize;
1127         if (Magic[0] == char(0xCE))
1128           MinSize = sizeof(MachO::mach_header);
1129         else
1130           MinSize = sizeof(MachO::mach_header_64);
1131         if (Magic.size() >= MinSize)
1132           type = Magic[15] << 24 | Magic[14] << 12 |Magic[13] << 8 | Magic[12];
1133       }
1134       switch (type) {
1135         default: break;
1136         case 1: return file_magic::macho_object;
1137         case 2: return file_magic::macho_executable;
1138         case 3: return file_magic::macho_fixed_virtual_memory_shared_lib;
1139         case 4: return file_magic::macho_core;
1140         case 5: return file_magic::macho_preload_executable;
1141         case 6: return file_magic::macho_dynamically_linked_shared_lib;
1142         case 7: return file_magic::macho_dynamic_linker;
1143         case 8: return file_magic::macho_bundle;
1144         case 9: return file_magic::macho_dynamically_linked_shared_lib_stub;
1145         case 10: return file_magic::macho_dsym_companion;
1146         case 11: return file_magic::macho_kext_bundle;
1147       }
1148       break;
1149     }
1150     case 0xF0: // PowerPC Windows
1151     case 0x83: // Alpha 32-bit
1152     case 0x84: // Alpha 64-bit
1153     case 0x66: // MPS R4000 Windows
1154     case 0x50: // mc68K
1155     case 0x4c: // 80386 Windows
1156     case 0xc4: // ARMNT Windows
1157       if (Magic[1] == 0x01)
1158         return file_magic::coff_object;
1159       LLVM_FALLTHROUGH;
1160
1161     case 0x90: // PA-RISC Windows
1162     case 0x68: // mc68K Windows
1163       if (Magic[1] == 0x02)
1164         return file_magic::coff_object;
1165       break;
1166
1167     case 'M': // Possible MS-DOS stub on Windows PE file
1168       if (startswith(Magic, "MZ")) {
1169         uint32_t off = read32le(Magic.data() + 0x3c);
1170         // PE/COFF file, either EXE or DLL.
1171         if (off < Magic.size() &&
1172             memcmp(Magic.data()+off, COFF::PEMagic, sizeof(COFF::PEMagic)) == 0)
1173           return file_magic::pecoff_executable;
1174       }
1175       break;
1176
1177     case 0x64: // x86-64 Windows.
1178       if (Magic[1] == char(0x86))
1179         return file_magic::coff_object;
1180       break;
1181
1182     default:
1183       break;
1184   }
1185   return file_magic::unknown;
1186 }
1187
1188 std::error_code identify_magic(const Twine &Path, file_magic &Result) {
1189   int FD;
1190   if (std::error_code EC = openFileForRead(Path, FD))
1191     return EC;
1192
1193   char Buffer[32];
1194   int Length = read(FD, Buffer, sizeof(Buffer));
1195   if (close(FD) != 0 || Length < 0)
1196     return std::error_code(errno, std::generic_category());
1197
1198   Result = identify_magic(StringRef(Buffer, Length));
1199   return std::error_code();
1200 }
1201
1202 std::error_code directory_entry::status(file_status &result) const {
1203   return fs::status(Path, result, FollowSymlinks);
1204 }
1205
1206 ErrorOr<perms> getPermissions(const Twine &Path) {
1207   file_status Status;
1208   if (std::error_code EC = status(Path, Status))
1209     return EC;
1210
1211   return Status.permissions();
1212 }
1213
1214 } // end namespace fs
1215 } // end namespace sys
1216 } // end namespace llvm
1217
1218 // Include the truly platform-specific parts.
1219 #if defined(LLVM_ON_UNIX)
1220 #include "Unix/Path.inc"
1221 #endif
1222 #if defined(LLVM_ON_WIN32)
1223 #include "Windows/Path.inc"
1224 #endif
1225
1226 namespace llvm {
1227 namespace sys {
1228 namespace path {
1229
1230 bool user_cache_directory(SmallVectorImpl<char> &Result, const Twine &Path1,
1231                           const Twine &Path2, const Twine &Path3) {
1232   if (getUserCacheDir(Result)) {
1233     append(Result, Path1, Path2, Path3);
1234     return true;
1235   }
1236   return false;
1237 }
1238
1239 } // end namespace path
1240 } // end namsspace sys
1241 } // end namespace llvm