1 //===-- Path.cpp - Implement OS Path Concept ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the operating system Path API.
12 //===----------------------------------------------------------------------===//
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"
25 #if !defined(_MSC_VER) && !defined(__MINGW32__)
34 using llvm::StringRef;
35 using llvm::sys::path::is_separator;
38 const char *separators = "\\/";
39 const char preferred_separator = '\\';
41 const char separators = '/';
42 const char preferred_separator = '/';
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.
51 // * {file,directory}name
58 if (path.size() >= 2 && std::isalpha(static_cast<unsigned char>(path[0])) &&
60 return path.substr(0, 2);
64 if ((path.size() > 2) &&
65 is_separator(path[0]) &&
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);
74 if (is_separator(path[0]))
75 return path.substr(0, 1);
77 if (path.startswith(".."))
78 return path.substr(0, 2);
81 return path.substr(0, 1);
83 // * {file,directory}name
84 size_t end = path.find_first_of(separators);
85 return path.substr(0, end);
88 size_t filename_pos(StringRef str) {
89 if (str.size() == 2 &&
90 is_separator(str[0]) &&
94 if (str.size() > 0 && is_separator(str[str.size() - 1]))
95 return str.size() - 1;
97 size_t pos = str.find_last_of(separators, str.size() - 1);
100 if (pos == StringRef::npos)
101 pos = str.find_last_of(':', str.size() - 2);
104 if (pos == StringRef::npos ||
105 (pos == 1 && is_separator(str[0])))
111 size_t root_dir_start(StringRef str) {
114 if (str.size() > 2 &&
116 is_separator(str[2]))
121 if (str.size() == 2 &&
122 is_separator(str[0]) &&
124 return StringRef::npos;
127 if (str.size() > 3 &&
128 is_separator(str[0]) &&
130 !is_separator(str[2])) {
131 return str.find_first_of(separators, 2);
135 if (str.size() > 0 && is_separator(str[0]))
138 return StringRef::npos;
141 size_t parent_path_end(StringRef path) {
142 size_t end_pos = filename_pos(path);
144 bool filename_was_sep = path.size() > 0 && is_separator(path[end_pos]);
146 // Skip separators except for root dir.
147 size_t root_dir_pos = root_dir_start(path.substr(0, end_pos));
150 (end_pos - 1) != root_dir_pos &&
151 is_separator(path[end_pos - 1]))
154 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
155 return StringRef::npos;
159 } // end unnamed namespace
167 // Implemented in Unix/Path.inc and Windows/Path.inc.
168 static std::error_code TempDir(SmallVectorImpl<char> &result);
170 static std::error_code createUniqueEntity(const Twine &Model, int &ResultFD,
171 SmallVectorImpl<char> &ResultPath,
172 bool MakeAbsolute, unsigned Mode,
174 SmallString<128> ModelStorage;
175 Model.toVector(ModelStorage);
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))
183 sys::path::append(TDir, Twine(ModelStorage));
184 ModelStorage.swap(TDir);
188 // From here on, DO NOT modify model. It may be needed if the randomly chosen
189 // path already exists.
190 ResultPath = ModelStorage;
192 ResultPath.push_back(0);
193 ResultPath.pop_back();
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];
202 // Try to open + create the 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;
213 return std::error_code();
218 std::error_code EC = sys::fs::exists(ResultPath.begin(), Exists);
222 goto retry_random_path;
223 return std::error_code();
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;
233 return std::error_code();
236 llvm_unreachable("Invalid Type");
243 const_iterator begin(StringRef path) {
246 i.Component = find_first_component(path);
251 const_iterator end(StringRef path) {
254 i.Position = path.size();
258 const_iterator &const_iterator::operator++() {
259 assert(Position < Path.size() && "Tried to increment past end!");
261 // Increment Position to past the current component
262 Position += Component.size();
265 if (Position == Path.size()) {
266 Component = StringRef();
270 // Both POSIX and Windows treat paths that begin with exactly two separators
272 bool was_net = Component.size() > 2 &&
273 is_separator(Component[0]) &&
274 Component[1] == Component[0] &&
275 !is_separator(Component[2]);
277 // Handle separators.
278 if (is_separator(Path[Position])) {
283 || Component.endswith(":")
286 Component = Path.substr(Position, 1);
290 // Skip extra separators.
291 while (Position != Path.size() &&
292 is_separator(Path[Position])) {
296 // Treat trailing '/' as a '.'.
297 if (Position == Path.size()) {
304 // Find next component.
305 size_t end_pos = Path.find_first_of(separators, Position);
306 Component = Path.slice(Position, end_pos);
311 bool const_iterator::operator==(const const_iterator &RHS) const {
312 return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
315 ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
316 return Position - RHS.Position;
319 reverse_iterator rbegin(StringRef Path) {
322 I.Position = Path.size();
326 reverse_iterator rend(StringRef Path) {
329 I.Component = Path.substr(0, 0);
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])) {
346 // Skip separators unless it's the root directory.
347 size_t end_pos = Position;
350 (end_pos - 1) != root_dir_pos &&
351 is_separator(Path[end_pos - 1]))
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;
361 bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
362 return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
363 Position == RHS.Position;
366 const StringRef root_path(StringRef path) {
367 const_iterator b = begin(path),
371 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
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());
384 // just {C:,//net}, return the first component.
389 // POSIX style root directory.
390 if (is_separator((*b)[0])) {
398 const StringRef root_name(StringRef path) {
399 const_iterator b = begin(path),
402 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
410 if (has_net || has_drive) {
411 // just {C:,//net}, return the first component.
416 // No path or no name.
420 const StringRef root_directory(StringRef path) {
421 const_iterator b = begin(path),
425 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
433 if ((has_net || has_drive) &&
434 // {C:,//net}, skip to the next component.
435 (++pos != e) && is_separator((*pos)[0])) {
439 // POSIX style root directory.
440 if (!has_net && is_separator((*b)[0])) {
445 // No path or no root.
449 const StringRef relative_path(StringRef path) {
450 StringRef root = root_path(path);
451 return path.substr(root.size());
454 void append(SmallVectorImpl<char> &path, const Twine &a,
458 SmallString<32> a_storage;
459 SmallString<32> b_storage;
460 SmallString<32> c_storage;
461 SmallString<32> d_storage;
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));
469 for (SmallVectorImpl<StringRef>::const_iterator i = components.begin(),
470 e = components.end();
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);
477 // Strip separators from beginning of component.
478 size_t loc = i->find_first_not_of(separators);
479 StringRef c = i->substr(loc);
482 path.append(c.begin(), c.end());
486 if (!component_has_sep && !(path.empty() || is_root_name)) {
488 path.push_back(preferred_separator);
491 path.append(i->begin(), i->end());
495 void append(SmallVectorImpl<char> &path,
496 const_iterator begin, const_iterator end) {
497 for (; begin != end; ++begin)
498 path::append(path, *begin);
501 const StringRef parent_path(StringRef path) {
502 size_t end_pos = parent_path_end(path);
503 if (end_pos == StringRef::npos)
506 return path.substr(0, end_pos);
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);
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);
520 // Erase existing extension.
521 size_t pos = p.find_last_of('.');
522 if (pos != StringRef::npos && pos >= filename_pos(p))
525 // Append '.' if needed.
526 if (ext.size() > 0 && ext[0] != '.')
530 path.append(ext.begin(), ext.end());
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!");
539 path.toVector(result);
543 void native(SmallVectorImpl<char> &Path) {
545 std::replace(path.begin(), path.end(), '/', '\\');
547 for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
550 if (PN < PE && *PN == '\\')
551 ++PI; // increment once, the for loop will move over the escaped slash
559 const StringRef filename(StringRef path) {
560 return *rbegin(path);
563 const StringRef stem(StringRef path) {
564 StringRef fname = filename(path);
565 size_t pos = fname.find_last_of('.');
566 if (pos == StringRef::npos)
569 if ((fname.size() == 1 && fname == ".") ||
570 (fname.size() == 2 && fname == ".."))
573 return fname.substr(0, pos);
576 const StringRef extension(StringRef path) {
577 StringRef fname = filename(path);
578 size_t pos = fname.find_last_of('.');
579 if (pos == StringRef::npos)
582 if ((fname.size() == 1 && fname == ".") ||
583 (fname.size() == 2 && fname == ".."))
586 return fname.substr(pos);
589 bool is_separator(char value) {
592 case '\\': // fall through
594 case '/': return true;
595 default: return false;
599 static const char preferred_separator_string[] = { preferred_separator, '\0' };
601 const StringRef get_separator() {
602 return preferred_separator_string;
605 void system_temp_directory(bool erasedOnReboot, SmallVectorImpl<char> &result) {
608 #if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
609 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
610 // macros defined in <unistd.h> on darwin >= 9
611 int ConfName = erasedOnReboot? _CS_DARWIN_USER_TEMP_DIR
612 : _CS_DARWIN_USER_CACHE_DIR;
613 size_t ConfLen = confstr(ConfName, nullptr, 0);
616 result.resize(ConfLen);
617 ConfLen = confstr(ConfName, result.data(), result.size());
618 } while (ConfLen > 0 && ConfLen != result.size());
621 assert(result.back() == 0);
630 // Check whether the temporary directory is specified by an environment
632 const char *EnvironmentVariable;
634 EnvironmentVariable = "TEMP";
636 EnvironmentVariable = "TMPDIR";
638 if (char *RequestedDir = getenv(EnvironmentVariable)) {
639 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
643 // Fall back to a system default.
644 const char *DefaultResult;
646 (void)erasedOnReboot;
647 DefaultResult = "C:\\TEMP";
650 DefaultResult = "/tmp";
652 DefaultResult = "/var/tmp";
654 result.append(DefaultResult, DefaultResult + strlen(DefaultResult));
657 bool has_root_name(const Twine &path) {
658 SmallString<128> path_storage;
659 StringRef p = path.toStringRef(path_storage);
661 return !root_name(p).empty();
664 bool has_root_directory(const Twine &path) {
665 SmallString<128> path_storage;
666 StringRef p = path.toStringRef(path_storage);
668 return !root_directory(p).empty();
671 bool has_root_path(const Twine &path) {
672 SmallString<128> path_storage;
673 StringRef p = path.toStringRef(path_storage);
675 return !root_path(p).empty();
678 bool has_relative_path(const Twine &path) {
679 SmallString<128> path_storage;
680 StringRef p = path.toStringRef(path_storage);
682 return !relative_path(p).empty();
685 bool has_filename(const Twine &path) {
686 SmallString<128> path_storage;
687 StringRef p = path.toStringRef(path_storage);
689 return !filename(p).empty();
692 bool has_parent_path(const Twine &path) {
693 SmallString<128> path_storage;
694 StringRef p = path.toStringRef(path_storage);
696 return !parent_path(p).empty();
699 bool has_stem(const Twine &path) {
700 SmallString<128> path_storage;
701 StringRef p = path.toStringRef(path_storage);
703 return !stem(p).empty();
706 bool has_extension(const Twine &path) {
707 SmallString<128> path_storage;
708 StringRef p = path.toStringRef(path_storage);
710 return !extension(p).empty();
713 bool is_absolute(const Twine &path) {
714 SmallString<128> path_storage;
715 StringRef p = path.toStringRef(path_storage);
717 bool rootDir = has_root_directory(p),
719 rootName = has_root_name(p);
724 return rootDir && rootName;
727 bool is_relative(const Twine &path) {
728 return !is_absolute(path);
731 } // end namespace path
735 std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
737 std::error_code EC = status(Path, Status);
740 Result = Status.getUniqueID();
741 return std::error_code();
744 std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
745 SmallVectorImpl<char> &ResultPath,
747 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
750 std::error_code createUniqueFile(const Twine &Model,
751 SmallVectorImpl<char> &ResultPath) {
753 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
756 static std::error_code
757 createTemporaryFile(const Twine &Model, int &ResultFD,
758 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
759 SmallString<128> Storage;
760 StringRef P = Model.toNullTerminatedStringRef(Storage);
761 assert(P.find_first_of(separators) == StringRef::npos &&
762 "Model must be a simple filename.");
763 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
764 return createUniqueEntity(P.begin(), ResultFD, ResultPath,
765 true, owner_read | owner_write, Type);
768 static std::error_code
769 createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
770 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
771 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
772 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
776 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
778 SmallVectorImpl<char> &ResultPath) {
779 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
782 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
783 SmallVectorImpl<char> &ResultPath) {
785 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
789 // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
790 // for consistency. We should try using mkdtemp.
791 std::error_code createUniqueDirectory(const Twine &Prefix,
792 SmallVectorImpl<char> &ResultPath) {
794 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
798 std::error_code make_absolute(SmallVectorImpl<char> &path) {
799 StringRef p(path.data(), path.size());
801 bool rootDirectory = path::has_root_directory(p),
803 rootName = path::has_root_name(p);
809 if (rootName && rootDirectory)
810 return std::error_code();
812 // All of the following conditions will need the current directory.
813 SmallString<128> current_dir;
814 if (std::error_code ec = current_path(current_dir))
817 // Relative path. Prepend the current directory.
818 if (!rootName && !rootDirectory) {
819 // Append path to the current directory.
820 path::append(current_dir, p);
821 // Set path to the result.
822 path.swap(current_dir);
823 return std::error_code();
826 if (!rootName && rootDirectory) {
827 StringRef cdrn = path::root_name(current_dir);
828 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
829 path::append(curDirRootName, p);
830 // Set path to the result.
831 path.swap(curDirRootName);
832 return std::error_code();
835 if (rootName && !rootDirectory) {
836 StringRef pRootName = path::root_name(p);
837 StringRef bRootDirectory = path::root_directory(current_dir);
838 StringRef bRelativePath = path::relative_path(current_dir);
839 StringRef pRelativePath = path::relative_path(p);
841 SmallString<128> res;
842 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
844 return std::error_code();
847 llvm_unreachable("All rootName and rootDirectory combinations should have "
851 std::error_code create_directories(const Twine &Path, bool IgnoreExisting) {
852 SmallString<128> PathStorage;
853 StringRef P = Path.toStringRef(PathStorage);
855 // Be optimistic and try to create the directory
856 std::error_code EC = create_directory(P, IgnoreExisting);
857 // If we succeeded, or had any error other than the parent not existing, just
859 if (EC != errc::no_such_file_or_directory)
862 // We failed because of a no_such_file_or_directory, try to create the
864 StringRef Parent = path::parent_path(P);
868 if ((EC = create_directories(Parent)))
871 return create_directory(P, IgnoreExisting);
874 std::error_code copy_file(const Twine &From, const Twine &To) {
876 if (std::error_code EC = openFileForRead(From, ReadFD))
878 if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
883 const size_t BufSize = 4096;
884 char *Buf = new char[BufSize];
885 int BytesRead = 0, BytesWritten = 0;
887 BytesRead = read(ReadFD, Buf, BufSize);
891 BytesWritten = write(WriteFD, Buf, BytesRead);
892 if (BytesWritten < 0)
894 BytesRead -= BytesWritten;
896 if (BytesWritten < 0)
903 if (BytesRead < 0 || BytesWritten < 0)
904 return std::error_code(errno, std::generic_category());
905 return std::error_code();
908 bool exists(file_status status) {
909 return status_known(status) && status.type() != file_type::file_not_found;
912 bool status_known(file_status s) {
913 return s.type() != file_type::status_error;
916 bool is_directory(file_status status) {
917 return status.type() == file_type::directory_file;
920 std::error_code is_directory(const Twine &path, bool &result) {
922 if (std::error_code ec = status(path, st))
924 result = is_directory(st);
925 return std::error_code();
928 bool is_regular_file(file_status status) {
929 return status.type() == file_type::regular_file;
932 std::error_code is_regular_file(const Twine &path, bool &result) {
934 if (std::error_code ec = status(path, st))
936 result = is_regular_file(st);
937 return std::error_code();
940 bool is_other(file_status status) {
941 return exists(status) &&
942 !is_regular_file(status) &&
943 !is_directory(status);
946 void directory_entry::replace_filename(const Twine &filename, file_status st) {
947 SmallString<128> path(Path.begin(), Path.end());
948 path::remove_filename(path);
949 path::append(path, filename);
954 /// @brief Identify the magic in magic.
955 file_magic identify_magic(StringRef Magic) {
956 if (Magic.size() < 4)
957 return file_magic::unknown;
958 switch ((unsigned char)Magic[0]) {
960 // COFF short import library file
961 if (Magic[1] == (char)0x00 && Magic[2] == (char)0xff &&
962 Magic[3] == (char)0xff)
963 return file_magic::coff_import_library;
964 // Windows resource file
965 const char Expected[] = { 0, 0, 0, 0, '\x20', 0, 0, 0, '\xff' };
966 if (Magic.size() >= sizeof(Expected) &&
967 memcmp(Magic.data(), Expected, sizeof(Expected)) == 0)
968 return file_magic::windows_resource;
969 // 0x0000 = COFF unknown machine type
971 return file_magic::coff_object;
974 case 0xDE: // 0x0B17C0DE = BC wraper
975 if (Magic[1] == (char)0xC0 && Magic[2] == (char)0x17 &&
976 Magic[3] == (char)0x0B)
977 return file_magic::bitcode;
980 if (Magic[1] == 'C' && Magic[2] == (char)0xC0 && Magic[3] == (char)0xDE)
981 return file_magic::bitcode;
984 if (Magic.size() >= 8)
985 if (memcmp(Magic.data(),"!<arch>\n",8) == 0)
986 return file_magic::archive;
990 if (Magic.size() >= 18 && Magic[1] == 'E' && Magic[2] == 'L' &&
992 bool Data2MSB = Magic[5] == 2;
993 unsigned high = Data2MSB ? 16 : 17;
994 unsigned low = Data2MSB ? 17 : 16;
995 if (Magic[high] == 0)
996 switch (Magic[low]) {
998 case 1: return file_magic::elf_relocatable;
999 case 2: return file_magic::elf_executable;
1000 case 3: return file_magic::elf_shared_object;
1001 case 4: return file_magic::elf_core;
1007 if (Magic[1] == char(0xFE) && Magic[2] == char(0xBA) &&
1008 Magic[3] == char(0xBE)) {
1009 // This is complicated by an overlap with Java class files.
1010 // See the Mach-O section in /usr/share/file/magic for details.
1011 if (Magic.size() >= 8 && Magic[7] < 43)
1012 return file_magic::macho_universal_binary;
1016 // The two magic numbers for mach-o are:
1017 // 0xfeedface - 32-bit mach-o
1018 // 0xfeedfacf - 64-bit mach-o
1023 if (Magic[0] == char(0xFE) && Magic[1] == char(0xED) &&
1024 Magic[2] == char(0xFA) &&
1025 (Magic[3] == char(0xCE) || Magic[3] == char(0xCF))) {
1027 if (Magic.size() >= 16) type = Magic[14] << 8 | Magic[15];
1028 } else if ((Magic[0] == char(0xCE) || Magic[0] == char(0xCF)) &&
1029 Magic[1] == char(0xFA) && Magic[2] == char(0xED) &&
1030 Magic[3] == char(0xFE)) {
1031 /* Reverse endian */
1032 if (Magic.size() >= 14) type = Magic[13] << 8 | Magic[12];
1036 case 1: return file_magic::macho_object;
1037 case 2: return file_magic::macho_executable;
1038 case 3: return file_magic::macho_fixed_virtual_memory_shared_lib;
1039 case 4: return file_magic::macho_core;
1040 case 5: return file_magic::macho_preload_executable;
1041 case 6: return file_magic::macho_dynamically_linked_shared_lib;
1042 case 7: return file_magic::macho_dynamic_linker;
1043 case 8: return file_magic::macho_bundle;
1044 case 9: return file_magic::macho_dynamic_linker;
1045 case 10: return file_magic::macho_dsym_companion;
1049 case 0xF0: // PowerPC Windows
1050 case 0x83: // Alpha 32-bit
1051 case 0x84: // Alpha 64-bit
1052 case 0x66: // MPS R4000 Windows
1054 case 0x4c: // 80386 Windows
1055 case 0xc4: // ARMNT Windows
1056 if (Magic[1] == 0x01)
1057 return file_magic::coff_object;
1059 case 0x90: // PA-RISC Windows
1060 case 0x68: // mc68K Windows
1061 if (Magic[1] == 0x02)
1062 return file_magic::coff_object;
1065 case 0x4d: // Possible MS-DOS stub on Windows PE file
1066 if (Magic[1] == 0x5a) {
1068 *reinterpret_cast<const support::ulittle32_t*>(Magic.data() + 0x3c);
1069 // PE/COFF file, either EXE or DLL.
1070 if (off < Magic.size() && memcmp(Magic.data() + off, "PE\0\0",4) == 0)
1071 return file_magic::pecoff_executable;
1075 case 0x64: // x86-64 Windows.
1076 if (Magic[1] == char(0x86))
1077 return file_magic::coff_object;
1083 return file_magic::unknown;
1086 std::error_code identify_magic(const Twine &Path, file_magic &Result) {
1088 if (std::error_code EC = openFileForRead(Path, FD))
1092 int Length = read(FD, Buffer, sizeof(Buffer));
1093 if (close(FD) != 0 || Length < 0)
1094 return std::error_code(errno, std::generic_category());
1096 Result = identify_magic(StringRef(Buffer, Length));
1097 return std::error_code();
1100 std::error_code directory_entry::status(file_status &result) const {
1101 return fs::status(Path, result);
1104 } // end namespace fs
1105 } // end namespace sys
1106 } // end namespace llvm
1108 // Include the truly platform-specific parts.
1109 #if defined(LLVM_ON_UNIX)
1110 #include "Unix/Path.inc"
1112 #if defined(LLVM_ON_WIN32)
1113 #include "Windows/Path.inc"