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