Remove unique_file now that it is unused.
[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 error_code createUniqueFile(const Twine &Model, int &ResultFd,
641                             SmallVectorImpl<char> &ResultPath, unsigned Mode) {
642   return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
643 }
644
645 error_code createUniqueFile(const Twine &Model,
646                             SmallVectorImpl<char> &ResultPath) {
647   int Dummy;
648   return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
649 }
650
651 static error_code createTemporaryFile(const Twine &Model, int &ResultFD,
652                                       llvm::SmallVectorImpl<char> &ResultPath,
653                                       FSEntity Type) {
654   SmallString<128> Storage;
655   StringRef P = Model.toNullTerminatedStringRef(Storage);
656   assert(P.find_first_of(separators) == StringRef::npos &&
657          "Model must be a simple filename.");
658   // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
659   return createUniqueEntity(P.begin(), ResultFD, ResultPath,
660                             true, owner_read | owner_write, Type);
661 }
662
663 static error_code
664 createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
665                     llvm::SmallVectorImpl<char> &ResultPath,
666                     FSEntity Type) {
667   return createTemporaryFile(Prefix + "-%%%%%%." + Suffix, ResultFD, ResultPath,
668                              Type);
669 }
670
671
672 error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
673                                int &ResultFD,
674                                SmallVectorImpl<char> &ResultPath) {
675   return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
676 }
677
678 error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
679                                SmallVectorImpl<char> &ResultPath) {
680   int Dummy;
681   return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
682 }
683
684
685 // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
686 // for consistency. We should try using mkdtemp.
687 error_code createUniqueDirectory(const Twine &Prefix,
688                                  SmallVectorImpl<char> &ResultPath) {
689   int Dummy;
690   return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
691                             true, 0, FS_Dir);
692 }
693
694 error_code make_absolute(SmallVectorImpl<char> &path) {
695   StringRef p(path.data(), path.size());
696
697   bool rootDirectory = path::has_root_directory(p),
698 #ifdef LLVM_ON_WIN32
699        rootName = path::has_root_name(p);
700 #else
701        rootName = true;
702 #endif
703
704   // Already absolute.
705   if (rootName && rootDirectory)
706     return error_code::success();
707
708   // All of the following conditions will need the current directory.
709   SmallString<128> current_dir;
710   if (error_code ec = current_path(current_dir)) return ec;
711
712   // Relative path. Prepend the current directory.
713   if (!rootName && !rootDirectory) {
714     // Append path to the current directory.
715     path::append(current_dir, p);
716     // Set path to the result.
717     path.swap(current_dir);
718     return error_code::success();
719   }
720
721   if (!rootName && rootDirectory) {
722     StringRef cdrn = path::root_name(current_dir);
723     SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
724     path::append(curDirRootName, p);
725     // Set path to the result.
726     path.swap(curDirRootName);
727     return error_code::success();
728   }
729
730   if (rootName && !rootDirectory) {
731     StringRef pRootName      = path::root_name(p);
732     StringRef bRootDirectory = path::root_directory(current_dir);
733     StringRef bRelativePath  = path::relative_path(current_dir);
734     StringRef pRelativePath  = path::relative_path(p);
735
736     SmallString<128> res;
737     path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
738     path.swap(res);
739     return error_code::success();
740   }
741
742   llvm_unreachable("All rootName and rootDirectory combinations should have "
743                    "occurred above!");
744 }
745
746 error_code create_directories(const Twine &path, bool &existed) {
747   SmallString<128> path_storage;
748   StringRef p = path.toStringRef(path_storage);
749
750   StringRef parent = path::parent_path(p);
751   if (!parent.empty()) {
752     bool parent_exists;
753     if (error_code ec = fs::exists(parent, parent_exists)) return ec;
754
755     if (!parent_exists)
756       if (error_code ec = create_directories(parent, existed)) return ec;
757   }
758
759   return create_directory(p, existed);
760 }
761
762 bool exists(file_status status) {
763   return status_known(status) && status.type() != file_type::file_not_found;
764 }
765
766 bool status_known(file_status s) {
767   return s.type() != file_type::status_error;
768 }
769
770 bool is_directory(file_status status) {
771   return status.type() == file_type::directory_file;
772 }
773
774 error_code is_directory(const Twine &path, bool &result) {
775   file_status st;
776   if (error_code ec = status(path, st))
777     return ec;
778   result = is_directory(st);
779   return error_code::success();
780 }
781
782 bool is_regular_file(file_status status) {
783   return status.type() == file_type::regular_file;
784 }
785
786 error_code is_regular_file(const Twine &path, bool &result) {
787   file_status st;
788   if (error_code ec = status(path, st))
789     return ec;
790   result = is_regular_file(st);
791   return error_code::success();
792 }
793
794 bool is_symlink(file_status status) {
795   return status.type() == file_type::symlink_file;
796 }
797
798 error_code is_symlink(const Twine &path, bool &result) {
799   file_status st;
800   if (error_code ec = status(path, st))
801     return ec;
802   result = is_symlink(st);
803   return error_code::success();
804 }
805
806 bool is_other(file_status status) {
807   return exists(status) &&
808          !is_regular_file(status) &&
809          !is_directory(status) &&
810          !is_symlink(status);
811 }
812
813 void directory_entry::replace_filename(const Twine &filename, file_status st) {
814   SmallString<128> path(Path.begin(), Path.end());
815   path::remove_filename(path);
816   path::append(path, filename);
817   Path = path.str();
818   Status = st;
819 }
820
821 error_code has_magic(const Twine &path, const Twine &magic, bool &result) {
822   SmallString<32>  MagicStorage;
823   StringRef Magic = magic.toStringRef(MagicStorage);
824   SmallString<32> Buffer;
825
826   if (error_code ec = get_magic(path, Magic.size(), Buffer)) {
827     if (ec == errc::value_too_large) {
828       // Magic.size() > file_size(Path).
829       result = false;
830       return error_code::success();
831     }
832     return ec;
833   }
834
835   result = Magic == Buffer;
836   return error_code::success();
837 }
838
839 /// @brief Identify the magic in magic.
840   file_magic identify_magic(StringRef Magic) {
841   if (Magic.size() < 4)
842     return file_magic::unknown;
843   switch ((unsigned char)Magic[0]) {
844     case 0xDE:  // 0x0B17C0DE = BC wraper
845       if (Magic[1] == (char)0xC0 && Magic[2] == (char)0x17 &&
846           Magic[3] == (char)0x0B)
847         return file_magic::bitcode;
848       break;
849     case 'B':
850       if (Magic[1] == 'C' && Magic[2] == (char)0xC0 && Magic[3] == (char)0xDE)
851         return file_magic::bitcode;
852       break;
853     case '!':
854       if (Magic.size() >= 8)
855         if (memcmp(Magic.data(),"!<arch>\n",8) == 0)
856           return file_magic::archive;
857       break;
858
859     case '\177':
860       if (Magic.size() >= 18 && Magic[1] == 'E' && Magic[2] == 'L' &&
861           Magic[3] == 'F') {
862         bool Data2MSB = Magic[5] == 2;
863         unsigned high = Data2MSB ? 16 : 17;
864         unsigned low  = Data2MSB ? 17 : 16;
865         if (Magic[high] == 0)
866           switch (Magic[low]) {
867             default: break;
868             case 1: return file_magic::elf_relocatable;
869             case 2: return file_magic::elf_executable;
870             case 3: return file_magic::elf_shared_object;
871             case 4: return file_magic::elf_core;
872           }
873       }
874       break;
875
876     case 0xCA:
877       if (Magic[1] == char(0xFE) && Magic[2] == char(0xBA) &&
878           Magic[3] == char(0xBE)) {
879         // This is complicated by an overlap with Java class files.
880         // See the Mach-O section in /usr/share/file/magic for details.
881         if (Magic.size() >= 8 && Magic[7] < 43)
882           return file_magic::macho_universal_binary;
883       }
884       break;
885
886       // The two magic numbers for mach-o are:
887       // 0xfeedface - 32-bit mach-o
888       // 0xfeedfacf - 64-bit mach-o
889     case 0xFE:
890     case 0xCE:
891     case 0xCF: {
892       uint16_t type = 0;
893       if (Magic[0] == char(0xFE) && Magic[1] == char(0xED) &&
894           Magic[2] == char(0xFA) &&
895           (Magic[3] == char(0xCE) || Magic[3] == char(0xCF))) {
896         /* Native endian */
897         if (Magic.size() >= 16) type = Magic[14] << 8 | Magic[15];
898       } else if ((Magic[0] == char(0xCE) || Magic[0] == char(0xCF)) &&
899                  Magic[1] == char(0xFA) && Magic[2] == char(0xED) &&
900                  Magic[3] == char(0xFE)) {
901         /* Reverse endian */
902         if (Magic.size() >= 14) type = Magic[13] << 8 | Magic[12];
903       }
904       switch (type) {
905         default: break;
906         case 1: return file_magic::macho_object;
907         case 2: return file_magic::macho_executable;
908         case 3: return file_magic::macho_fixed_virtual_memory_shared_lib;
909         case 4: return file_magic::macho_core;
910         case 5: return file_magic::macho_preload_executable;
911         case 6: return file_magic::macho_dynamically_linked_shared_lib;
912         case 7: return file_magic::macho_dynamic_linker;
913         case 8: return file_magic::macho_bundle;
914         case 9: return file_magic::macho_dynamic_linker;
915         case 10: return file_magic::macho_dsym_companion;
916       }
917       break;
918     }
919     case 0xF0: // PowerPC Windows
920     case 0x83: // Alpha 32-bit
921     case 0x84: // Alpha 64-bit
922     case 0x66: // MPS R4000 Windows
923     case 0x50: // mc68K
924     case 0x4c: // 80386 Windows
925       if (Magic[1] == 0x01)
926         return file_magic::coff_object;
927
928     case 0x90: // PA-RISC Windows
929     case 0x68: // mc68K Windows
930       if (Magic[1] == 0x02)
931         return file_magic::coff_object;
932       break;
933
934     case 0x4d: // Possible MS-DOS stub on Windows PE file
935       if (Magic[1] == 0x5a) {
936         uint32_t off =
937           *reinterpret_cast<const support::ulittle32_t*>(Magic.data() + 0x3c);
938         // PE/COFF file, either EXE or DLL.
939         if (off < Magic.size() && memcmp(Magic.data() + off, "PE\0\0",4) == 0)
940           return file_magic::pecoff_executable;
941       }
942       break;
943
944     case 0x64: // x86-64 Windows.
945       if (Magic[1] == char(0x86))
946         return file_magic::coff_object;
947       break;
948
949     default:
950       break;
951   }
952   return file_magic::unknown;
953 }
954
955 error_code identify_magic(const Twine &path, file_magic &result) {
956   SmallString<32> Magic;
957   error_code ec = get_magic(path, Magic.capacity(), Magic);
958   if (ec && ec != errc::value_too_large)
959     return ec;
960
961   result = identify_magic(Magic);
962   return error_code::success();
963 }
964
965 namespace {
966 error_code remove_all_r(StringRef path, file_type ft, uint32_t &count) {
967   if (ft == file_type::directory_file) {
968     // This code would be a lot better with exceptions ;/.
969     error_code ec;
970     directory_iterator i(path, ec);
971     if (ec) return ec;
972     for (directory_iterator e; i != e; i.increment(ec)) {
973       if (ec) return ec;
974       file_status st;
975       if (error_code ec = i->status(st)) return ec;
976       if (error_code ec = remove_all_r(i->path(), st.type(), count)) return ec;
977     }
978     bool obviously_this_exists;
979     if (error_code ec = remove(path, obviously_this_exists)) return ec;
980     assert(obviously_this_exists);
981     ++count; // Include the directory itself in the items removed.
982   } else {
983     bool obviously_this_exists;
984     if (error_code ec = remove(path, obviously_this_exists)) return ec;
985     assert(obviously_this_exists);
986     ++count;
987   }
988
989   return error_code::success();
990 }
991 } // end unnamed namespace
992
993 error_code remove_all(const Twine &path, uint32_t &num_removed) {
994   SmallString<128> path_storage;
995   StringRef p = path.toStringRef(path_storage);
996
997   file_status fs;
998   if (error_code ec = status(path, fs))
999     return ec;
1000   num_removed = 0;
1001   return remove_all_r(p, fs.type(), num_removed);
1002 }
1003
1004 error_code directory_entry::status(file_status &result) const {
1005   return fs::status(Path, result);
1006 }
1007
1008 } // end namespace fs
1009 } // end namespace sys
1010 } // end namespace llvm
1011
1012 // Include the truly platform-specific parts.
1013 #if defined(LLVM_ON_UNIX)
1014 #include "Unix/Path.inc"
1015 #endif
1016 #if defined(LLVM_ON_WIN32)
1017 #include "Windows/Path.inc"
1018 #endif