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