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