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