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