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/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"
24 #if !defined(_MSC_VER) && !defined(__MINGW32__)
31 using namespace llvm::support::endian;
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.
50 // * {file,directory}name
57 if (path.size() >= 2 && std::isalpha(static_cast<unsigned char>(path[0])) &&
59 return path.substr(0, 2);
63 if ((path.size() > 2) &&
64 is_separator(path[0]) &&
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);
73 if (is_separator(path[0]))
74 return path.substr(0, 1);
76 // * {file,directory}name
77 size_t end = path.find_first_of(separators);
78 return path.substr(0, end);
81 size_t filename_pos(StringRef str) {
82 if (str.size() == 2 &&
83 is_separator(str[0]) &&
87 if (str.size() > 0 && is_separator(str[str.size() - 1]))
88 return str.size() - 1;
90 size_t pos = str.find_last_of(separators, str.size() - 1);
93 if (pos == StringRef::npos)
94 pos = str.find_last_of(':', str.size() - 2);
97 if (pos == StringRef::npos ||
98 (pos == 1 && is_separator(str[0])))
104 size_t root_dir_start(StringRef str) {
107 if (str.size() > 2 &&
109 is_separator(str[2]))
114 if (str.size() == 2 &&
115 is_separator(str[0]) &&
117 return StringRef::npos;
120 if (str.size() > 3 &&
121 is_separator(str[0]) &&
123 !is_separator(str[2])) {
124 return str.find_first_of(separators, 2);
128 if (str.size() > 0 && is_separator(str[0]))
131 return StringRef::npos;
134 size_t parent_path_end(StringRef path) {
135 size_t end_pos = filename_pos(path);
137 bool filename_was_sep = path.size() > 0 && is_separator(path[end_pos]);
139 // Skip separators except for root dir.
140 size_t root_dir_pos = root_dir_start(path.substr(0, end_pos));
143 (end_pos - 1) != root_dir_pos &&
144 is_separator(path[end_pos - 1]))
147 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
148 return StringRef::npos;
152 } // end unnamed namespace
160 static std::error_code createUniqueEntity(const Twine &Model, int &ResultFD,
161 SmallVectorImpl<char> &ResultPath,
162 bool MakeAbsolute, unsigned Mode,
164 SmallString<128> ModelStorage;
165 Model.toVector(ModelStorage);
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);
177 // From here on, DO NOT modify model. It may be needed if the randomly chosen
178 // path already exists.
179 ResultPath = ModelStorage;
181 ResultPath.push_back(0);
182 ResultPath.pop_back();
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];
191 // Try to open + create the 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;
202 return std::error_code();
207 sys::fs::access(ResultPath.begin(), sys::fs::AccessMode::Exist);
208 if (EC == errc::no_such_file_or_directory)
209 return std::error_code();
212 goto retry_random_path;
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;
222 return std::error_code();
225 llvm_unreachable("Invalid Type");
232 const_iterator begin(StringRef path) {
235 i.Component = find_first_component(path);
240 const_iterator end(StringRef path) {
243 i.Position = path.size();
247 const_iterator &const_iterator::operator++() {
248 assert(Position < Path.size() && "Tried to increment past end!");
250 // Increment Position to past the current component
251 Position += Component.size();
254 if (Position == Path.size()) {
255 Component = StringRef();
259 // Both POSIX and Windows treat paths that begin with exactly two separators
261 bool was_net = Component.size() > 2 &&
262 is_separator(Component[0]) &&
263 Component[1] == Component[0] &&
264 !is_separator(Component[2]);
266 // Handle separators.
267 if (is_separator(Path[Position])) {
272 || Component.endswith(":")
275 Component = Path.substr(Position, 1);
279 // Skip extra separators.
280 while (Position != Path.size() &&
281 is_separator(Path[Position])) {
285 // Treat trailing '/' as a '.'.
286 if (Position == Path.size()) {
293 // Find next component.
294 size_t end_pos = Path.find_first_of(separators, Position);
295 Component = Path.slice(Position, end_pos);
300 bool const_iterator::operator==(const const_iterator &RHS) const {
301 return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
304 ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
305 return Position - RHS.Position;
308 reverse_iterator rbegin(StringRef Path) {
311 I.Position = Path.size();
315 reverse_iterator rend(StringRef Path) {
318 I.Component = Path.substr(0, 0);
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])) {
335 // Skip separators unless it's the root directory.
336 size_t end_pos = Position;
339 (end_pos - 1) != root_dir_pos &&
340 is_separator(Path[end_pos - 1]))
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;
350 bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
351 return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
352 Position == RHS.Position;
355 StringRef root_path(StringRef path) {
356 const_iterator b = begin(path),
360 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
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());
373 // just {C:,//net}, return the first component.
378 // POSIX style root directory.
379 if (is_separator((*b)[0])) {
387 StringRef root_name(StringRef path) {
388 const_iterator b = begin(path),
391 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
399 if (has_net || has_drive) {
400 // just {C:,//net}, return the first component.
405 // No path or no name.
409 StringRef root_directory(StringRef path) {
410 const_iterator b = begin(path),
414 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
422 if ((has_net || has_drive) &&
423 // {C:,//net}, skip to the next component.
424 (++pos != e) && is_separator((*pos)[0])) {
428 // POSIX style root directory.
429 if (!has_net && is_separator((*b)[0])) {
434 // No path or no root.
438 StringRef relative_path(StringRef path) {
439 StringRef root = root_path(path);
440 return path.substr(root.size());
443 void append(SmallVectorImpl<char> &path, const Twine &a,
447 SmallString<32> a_storage;
448 SmallString<32> b_storage;
449 SmallString<32> c_storage;
450 SmallString<32> d_storage;
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));
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);
464 // Strip separators from beginning of component.
465 size_t loc = component.find_first_not_of(separators);
466 StringRef c = component.substr(loc);
469 path.append(c.begin(), c.end());
473 if (!component_has_sep && !(path.empty() || is_root_name)) {
475 path.push_back(preferred_separator);
478 path.append(component.begin(), component.end());
482 void append(SmallVectorImpl<char> &path,
483 const_iterator begin, const_iterator end) {
484 for (; begin != end; ++begin)
485 path::append(path, *begin);
488 StringRef parent_path(StringRef path) {
489 size_t end_pos = parent_path_end(path);
490 if (end_pos == StringRef::npos)
493 return path.substr(0, end_pos);
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);
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);
507 // Erase existing extension.
508 size_t pos = p.find_last_of('.');
509 if (pos != StringRef::npos && pos >= filename_pos(p))
512 // Append '.' if needed.
513 if (ext.size() > 0 && ext[0] != '.')
517 path.append(ext.begin(), ext.end());
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!");
526 path.toVector(result);
530 void native(SmallVectorImpl<char> &Path) {
532 std::replace(Path.begin(), Path.end(), '/', '\\');
534 for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
537 if (PN < PE && *PN == '\\')
538 ++PI; // increment once, the for loop will move over the escaped slash
546 StringRef filename(StringRef path) {
547 return *rbegin(path);
550 StringRef stem(StringRef path) {
551 StringRef fname = filename(path);
552 size_t pos = fname.find_last_of('.');
553 if (pos == StringRef::npos)
556 if ((fname.size() == 1 && fname == ".") ||
557 (fname.size() == 2 && fname == ".."))
560 return fname.substr(0, pos);
563 StringRef extension(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(pos);
576 bool is_separator(char value) {
579 case '\\': // fall through
581 case '/': return true;
582 default: return false;
586 static const char preferred_separator_string[] = { preferred_separator, '\0' };
588 StringRef get_separator() {
589 return preferred_separator_string;
592 bool has_root_name(const Twine &path) {
593 SmallString<128> path_storage;
594 StringRef p = path.toStringRef(path_storage);
596 return !root_name(p).empty();
599 bool has_root_directory(const Twine &path) {
600 SmallString<128> path_storage;
601 StringRef p = path.toStringRef(path_storage);
603 return !root_directory(p).empty();
606 bool has_root_path(const Twine &path) {
607 SmallString<128> path_storage;
608 StringRef p = path.toStringRef(path_storage);
610 return !root_path(p).empty();
613 bool has_relative_path(const Twine &path) {
614 SmallString<128> path_storage;
615 StringRef p = path.toStringRef(path_storage);
617 return !relative_path(p).empty();
620 bool has_filename(const Twine &path) {
621 SmallString<128> path_storage;
622 StringRef p = path.toStringRef(path_storage);
624 return !filename(p).empty();
627 bool has_parent_path(const Twine &path) {
628 SmallString<128> path_storage;
629 StringRef p = path.toStringRef(path_storage);
631 return !parent_path(p).empty();
634 bool has_stem(const Twine &path) {
635 SmallString<128> path_storage;
636 StringRef p = path.toStringRef(path_storage);
638 return !stem(p).empty();
641 bool has_extension(const Twine &path) {
642 SmallString<128> path_storage;
643 StringRef p = path.toStringRef(path_storage);
645 return !extension(p).empty();
648 bool is_absolute(const Twine &path) {
649 SmallString<128> path_storage;
650 StringRef p = path.toStringRef(path_storage);
652 bool rootDir = has_root_directory(p),
654 rootName = has_root_name(p);
659 return rootDir && rootName;
662 bool is_relative(const Twine &path) { return !is_absolute(path); }
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);
674 static SmallString<256> remove_dots(StringRef path, bool remove_dot_dot) {
675 SmallVector<StringRef, 16> components;
677 // Skip the root path, then look for traversal in the components.
678 StringRef rel = path::relative_path(path);
679 for (StringRef C : llvm::make_range(path::begin(rel), path::end(rel))) {
682 if (remove_dot_dot) {
684 if (!components.empty())
685 components.pop_back();
689 components.push_back(C);
692 SmallString<256> buffer = path::root_path(path);
693 for (StringRef C : components)
694 path::append(buffer, C);
698 bool remove_dots(SmallVectorImpl<char> &path, bool remove_dot_dot) {
699 StringRef p(path.data(), path.size());
701 SmallString<256> result = remove_dots(p, remove_dot_dot);
709 } // end namespace path
713 std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
715 std::error_code EC = status(Path, Status);
718 Result = Status.getUniqueID();
719 return std::error_code();
722 std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
723 SmallVectorImpl<char> &ResultPath,
725 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
728 std::error_code createUniqueFile(const Twine &Model,
729 SmallVectorImpl<char> &ResultPath) {
731 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
734 static std::error_code
735 createTemporaryFile(const Twine &Model, int &ResultFD,
736 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
737 SmallString<128> Storage;
738 StringRef P = Model.toNullTerminatedStringRef(Storage);
739 assert(P.find_first_of(separators) == StringRef::npos &&
740 "Model must be a simple filename.");
741 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
742 return createUniqueEntity(P.begin(), ResultFD, ResultPath,
743 true, owner_read | owner_write, Type);
746 static std::error_code
747 createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
748 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
749 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
750 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
754 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
756 SmallVectorImpl<char> &ResultPath) {
757 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
760 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
761 SmallVectorImpl<char> &ResultPath) {
763 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
767 // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
768 // for consistency. We should try using mkdtemp.
769 std::error_code createUniqueDirectory(const Twine &Prefix,
770 SmallVectorImpl<char> &ResultPath) {
772 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
776 static std::error_code make_absolute(const Twine ¤t_directory,
777 SmallVectorImpl<char> &path,
778 bool use_current_directory) {
779 StringRef p(path.data(), path.size());
781 bool rootDirectory = path::has_root_directory(p),
783 rootName = path::has_root_name(p);
789 if (rootName && rootDirectory)
790 return std::error_code();
792 // All of the following conditions will need the current directory.
793 SmallString<128> current_dir;
794 if (use_current_directory)
795 current_directory.toVector(current_dir);
796 else if (std::error_code ec = current_path(current_dir))
799 // Relative path. Prepend the current directory.
800 if (!rootName && !rootDirectory) {
801 // Append path to the current directory.
802 path::append(current_dir, p);
803 // Set path to the result.
804 path.swap(current_dir);
805 return std::error_code();
808 if (!rootName && rootDirectory) {
809 StringRef cdrn = path::root_name(current_dir);
810 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
811 path::append(curDirRootName, p);
812 // Set path to the result.
813 path.swap(curDirRootName);
814 return std::error_code();
817 if (rootName && !rootDirectory) {
818 StringRef pRootName = path::root_name(p);
819 StringRef bRootDirectory = path::root_directory(current_dir);
820 StringRef bRelativePath = path::relative_path(current_dir);
821 StringRef pRelativePath = path::relative_path(p);
823 SmallString<128> res;
824 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
826 return std::error_code();
829 llvm_unreachable("All rootName and rootDirectory combinations should have "
833 std::error_code make_absolute(const Twine ¤t_directory,
834 SmallVectorImpl<char> &path) {
835 return make_absolute(current_directory, path, true);
838 std::error_code make_absolute(SmallVectorImpl<char> &path) {
839 return make_absolute(Twine(), path, false);
842 std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
844 SmallString<128> PathStorage;
845 StringRef P = Path.toStringRef(PathStorage);
847 // Be optimistic and try to create the directory
848 std::error_code EC = create_directory(P, IgnoreExisting, Perms);
849 // If we succeeded, or had any error other than the parent not existing, just
851 if (EC != errc::no_such_file_or_directory)
854 // We failed because of a no_such_file_or_directory, try to create the
856 StringRef Parent = path::parent_path(P);
860 if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
863 return create_directory(P, IgnoreExisting, Perms);
866 std::error_code copy_file(const Twine &From, const Twine &To) {
868 if (std::error_code EC = openFileForRead(From, ReadFD))
870 if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
875 const size_t BufSize = 4096;
876 char *Buf = new char[BufSize];
877 int BytesRead = 0, BytesWritten = 0;
879 BytesRead = read(ReadFD, Buf, BufSize);
883 BytesWritten = write(WriteFD, Buf, BytesRead);
884 if (BytesWritten < 0)
886 BytesRead -= BytesWritten;
888 if (BytesWritten < 0)
895 if (BytesRead < 0 || BytesWritten < 0)
896 return std::error_code(errno, std::generic_category());
897 return std::error_code();
900 bool exists(file_status status) {
901 return status_known(status) && status.type() != file_type::file_not_found;
904 bool status_known(file_status s) {
905 return s.type() != file_type::status_error;
908 bool is_directory(file_status status) {
909 return status.type() == file_type::directory_file;
912 std::error_code is_directory(const Twine &path, bool &result) {
914 if (std::error_code ec = status(path, st))
916 result = is_directory(st);
917 return std::error_code();
920 bool is_regular_file(file_status status) {
921 return status.type() == file_type::regular_file;
924 std::error_code is_regular_file(const Twine &path, bool &result) {
926 if (std::error_code ec = status(path, st))
928 result = is_regular_file(st);
929 return std::error_code();
932 bool is_other(file_status status) {
933 return exists(status) &&
934 !is_regular_file(status) &&
935 !is_directory(status);
938 std::error_code is_other(const Twine &Path, bool &Result) {
939 file_status FileStatus;
940 if (std::error_code EC = status(Path, FileStatus))
942 Result = is_other(FileStatus);
943 return std::error_code();
946 void directory_entry::replace_filename(const Twine &filename, file_status st) {
947 SmallString<128> path = path::parent_path(Path);
948 path::append(path, filename);
953 /// @brief Identify the magic in magic.
954 file_magic identify_magic(StringRef Magic) {
955 if (Magic.size() < 4)
956 return file_magic::unknown;
957 switch ((unsigned char)Magic[0]) {
959 // COFF bigobj or short import library file
960 if (Magic[1] == (char)0x00 && Magic[2] == (char)0xff &&
961 Magic[3] == (char)0xff) {
962 size_t MinSize = offsetof(COFF::BigObjHeader, UUID) + sizeof(COFF::BigObjMagic);
963 if (Magic.size() < MinSize)
964 return file_magic::coff_import_library;
966 int BigObjVersion = read16le(
967 Magic.data() + offsetof(COFF::BigObjHeader, Version));
968 if (BigObjVersion < COFF::BigObjHeader::MinBigObjectVersion)
969 return file_magic::coff_import_library;
971 const char *Start = Magic.data() + offsetof(COFF::BigObjHeader, UUID);
972 if (memcmp(Start, COFF::BigObjMagic, sizeof(COFF::BigObjMagic)) != 0)
973 return file_magic::coff_import_library;
974 return file_magic::coff_object;
976 // Windows resource file
977 const char Expected[] = { 0, 0, 0, 0, '\x20', 0, 0, 0, '\xff' };
978 if (Magic.size() >= sizeof(Expected) &&
979 memcmp(Magic.data(), Expected, sizeof(Expected)) == 0)
980 return file_magic::windows_resource;
981 // 0x0000 = COFF unknown machine type
983 return file_magic::coff_object;
986 case 0xDE: // 0x0B17C0DE = BC wraper
987 if (Magic[1] == (char)0xC0 && Magic[2] == (char)0x17 &&
988 Magic[3] == (char)0x0B)
989 return file_magic::bitcode;
992 if (Magic[1] == 'C' && Magic[2] == (char)0xC0 && Magic[3] == (char)0xDE)
993 return file_magic::bitcode;
996 if (Magic.size() >= 8)
997 if (memcmp(Magic.data(), "!<arch>\n", 8) == 0 ||
998 memcmp(Magic.data(), "!<thin>\n", 8) == 0)
999 return file_magic::archive;
1003 if (Magic.size() >= 18 && Magic[1] == 'E' && Magic[2] == 'L' &&
1005 bool Data2MSB = Magic[5] == 2;
1006 unsigned high = Data2MSB ? 16 : 17;
1007 unsigned low = Data2MSB ? 17 : 16;
1008 if (Magic[high] == 0)
1009 switch (Magic[low]) {
1010 default: return file_magic::elf;
1011 case 1: return file_magic::elf_relocatable;
1012 case 2: return file_magic::elf_executable;
1013 case 3: return file_magic::elf_shared_object;
1014 case 4: return file_magic::elf_core;
1017 // It's still some type of ELF file.
1018 return file_magic::elf;
1023 if (Magic[1] == char(0xFE) && Magic[2] == char(0xBA) &&
1024 Magic[3] == char(0xBE)) {
1025 // This is complicated by an overlap with Java class files.
1026 // See the Mach-O section in /usr/share/file/magic for details.
1027 if (Magic.size() >= 8 && Magic[7] < 43)
1028 return file_magic::macho_universal_binary;
1032 // The two magic numbers for mach-o are:
1033 // 0xfeedface - 32-bit mach-o
1034 // 0xfeedfacf - 64-bit mach-o
1039 if (Magic[0] == char(0xFE) && Magic[1] == char(0xED) &&
1040 Magic[2] == char(0xFA) &&
1041 (Magic[3] == char(0xCE) || Magic[3] == char(0xCF))) {
1043 if (Magic.size() >= 16) type = Magic[14] << 8 | Magic[15];
1044 } else if ((Magic[0] == char(0xCE) || Magic[0] == char(0xCF)) &&
1045 Magic[1] == char(0xFA) && Magic[2] == char(0xED) &&
1046 Magic[3] == char(0xFE)) {
1047 /* Reverse endian */
1048 if (Magic.size() >= 14) type = Magic[13] << 8 | Magic[12];
1052 case 1: return file_magic::macho_object;
1053 case 2: return file_magic::macho_executable;
1054 case 3: return file_magic::macho_fixed_virtual_memory_shared_lib;
1055 case 4: return file_magic::macho_core;
1056 case 5: return file_magic::macho_preload_executable;
1057 case 6: return file_magic::macho_dynamically_linked_shared_lib;
1058 case 7: return file_magic::macho_dynamic_linker;
1059 case 8: return file_magic::macho_bundle;
1060 case 9: return file_magic::macho_dynamically_linked_shared_lib_stub;
1061 case 10: return file_magic::macho_dsym_companion;
1062 case 11: return file_magic::macho_kext_bundle;
1066 case 0xF0: // PowerPC Windows
1067 case 0x83: // Alpha 32-bit
1068 case 0x84: // Alpha 64-bit
1069 case 0x66: // MPS R4000 Windows
1071 case 0x4c: // 80386 Windows
1072 case 0xc4: // ARMNT Windows
1073 if (Magic[1] == 0x01)
1074 return file_magic::coff_object;
1076 case 0x90: // PA-RISC Windows
1077 case 0x68: // mc68K Windows
1078 if (Magic[1] == 0x02)
1079 return file_magic::coff_object;
1082 case 'M': // Possible MS-DOS stub on Windows PE file
1083 if (Magic[1] == 'Z') {
1084 uint32_t off = read32le(Magic.data() + 0x3c);
1085 // PE/COFF file, either EXE or DLL.
1086 if (off < Magic.size() &&
1087 memcmp(Magic.data()+off, COFF::PEMagic, sizeof(COFF::PEMagic)) == 0)
1088 return file_magic::pecoff_executable;
1092 case 0x64: // x86-64 Windows.
1093 if (Magic[1] == char(0x86))
1094 return file_magic::coff_object;
1100 return file_magic::unknown;
1103 std::error_code identify_magic(const Twine &Path, file_magic &Result) {
1105 if (std::error_code EC = openFileForRead(Path, FD))
1109 int Length = read(FD, Buffer, sizeof(Buffer));
1110 if (close(FD) != 0 || Length < 0)
1111 return std::error_code(errno, std::generic_category());
1113 Result = identify_magic(StringRef(Buffer, Length));
1114 return std::error_code();
1117 std::error_code directory_entry::status(file_status &result) const {
1118 return fs::status(Path, result);
1121 } // end namespace fs
1122 } // end namespace sys
1123 } // end namespace llvm
1125 // Include the truly platform-specific parts.
1126 #if defined(LLVM_ON_UNIX)
1127 #include "Unix/Path.inc"
1129 #if defined(LLVM_ON_WIN32)
1130 #include "Windows/Path.inc"
1137 bool user_cache_directory(SmallVectorImpl<char> &Result, const Twine &Path1,
1138 const Twine &Path2, const Twine &Path3) {
1139 if (getUserCacheDir(Result)) {
1140 append(Result, Path1, Path2, Path3);
1146 } // end namespace path
1147 } // end namsspace sys
1148 } // end namespace llvm