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