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