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