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