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