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/MachO.h"
16 #include "llvm/Support/Endian.h"
17 #include "llvm/Support/Errc.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/Process.h"
25 #if !defined(_MSC_VER) && !defined(__MINGW32__)
32 using namespace llvm::support::endian;
35 using llvm::StringRef;
36 using llvm::sys::path::is_separator;
39 const char *separators = "\\/";
40 const char preferred_separator = '\\';
42 const char separators = '/';
43 const char preferred_separator = '/';
46 StringRef find_first_component(StringRef path) {
47 // Look for this first component in the following order.
48 // * empty (in this case we return an empty string)
49 // * 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 // * {file,directory}name
78 size_t end = path.find_first_of(separators);
79 return path.substr(0, end);
82 size_t filename_pos(StringRef str) {
83 if (str.size() == 2 &&
84 is_separator(str[0]) &&
88 if (str.size() > 0 && is_separator(str[str.size() - 1]))
89 return str.size() - 1;
91 size_t pos = str.find_last_of(separators, str.size() - 1);
94 if (pos == StringRef::npos)
95 pos = str.find_last_of(':', str.size() - 2);
98 if (pos == StringRef::npos ||
99 (pos == 1 && is_separator(str[0])))
105 size_t root_dir_start(StringRef str) {
108 if (str.size() > 2 &&
110 is_separator(str[2]))
115 if (str.size() == 2 &&
116 is_separator(str[0]) &&
118 return StringRef::npos;
121 if (str.size() > 3 &&
122 is_separator(str[0]) &&
124 !is_separator(str[2])) {
125 return str.find_first_of(separators, 2);
129 if (str.size() > 0 && is_separator(str[0]))
132 return StringRef::npos;
135 size_t parent_path_end(StringRef path) {
136 size_t end_pos = filename_pos(path);
138 bool filename_was_sep = path.size() > 0 && is_separator(path[end_pos]);
140 // Skip separators except for root dir.
141 size_t root_dir_pos = root_dir_start(path.substr(0, end_pos));
144 (end_pos - 1) != root_dir_pos &&
145 is_separator(path[end_pos - 1]))
148 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
149 return StringRef::npos;
153 } // end unnamed namespace
161 static std::error_code createUniqueEntity(const Twine &Model, int &ResultFD,
162 SmallVectorImpl<char> &ResultPath,
163 bool MakeAbsolute, unsigned Mode,
165 SmallString<128> ModelStorage;
166 Model.toVector(ModelStorage);
169 // Make model absolute by prepending a temp directory if it's not already.
170 if (!sys::path::is_absolute(Twine(ModelStorage))) {
171 SmallString<128> TDir;
172 sys::path::system_temp_directory(true, TDir);
173 sys::path::append(TDir, Twine(ModelStorage));
174 ModelStorage.swap(TDir);
178 // From here on, DO NOT modify model. It may be needed if the randomly chosen
179 // path already exists.
180 ResultPath = ModelStorage;
182 ResultPath.push_back(0);
183 ResultPath.pop_back();
186 // Replace '%' with random chars.
187 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
188 if (ModelStorage[i] == '%')
189 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
192 // Try to open + create the file.
195 if (std::error_code EC =
196 sys::fs::openFileForWrite(Twine(ResultPath.begin()), ResultFD,
197 sys::fs::F_RW | sys::fs::F_Excl, Mode)) {
198 if (EC == errc::file_exists)
199 goto retry_random_path;
203 return std::error_code();
208 sys::fs::access(ResultPath.begin(), sys::fs::AccessMode::Exist);
209 if (EC == errc::no_such_file_or_directory)
210 return std::error_code();
213 goto retry_random_path;
217 if (std::error_code EC =
218 sys::fs::create_directory(ResultPath.begin(), false)) {
219 if (EC == errc::file_exists)
220 goto retry_random_path;
223 return std::error_code();
226 llvm_unreachable("Invalid Type");
233 const_iterator begin(StringRef path) {
236 i.Component = find_first_component(path);
241 const_iterator end(StringRef path) {
244 i.Position = path.size();
248 const_iterator &const_iterator::operator++() {
249 assert(Position < Path.size() && "Tried to increment past end!");
251 // Increment Position to past the current component
252 Position += Component.size();
255 if (Position == Path.size()) {
256 Component = StringRef();
260 // Both POSIX and Windows treat paths that begin with exactly two separators
262 bool was_net = Component.size() > 2 &&
263 is_separator(Component[0]) &&
264 Component[1] == Component[0] &&
265 !is_separator(Component[2]);
267 // Handle separators.
268 if (is_separator(Path[Position])) {
273 || Component.endswith(":")
276 Component = Path.substr(Position, 1);
280 // Skip extra separators.
281 while (Position != Path.size() &&
282 is_separator(Path[Position])) {
286 // Treat trailing '/' as a '.'.
287 if (Position == Path.size()) {
294 // Find next component.
295 size_t end_pos = Path.find_first_of(separators, Position);
296 Component = Path.slice(Position, end_pos);
301 bool const_iterator::operator==(const const_iterator &RHS) const {
302 return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
305 ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
306 return Position - RHS.Position;
309 reverse_iterator rbegin(StringRef Path) {
312 I.Position = Path.size();
316 reverse_iterator rend(StringRef Path) {
319 I.Component = Path.substr(0, 0);
324 reverse_iterator &reverse_iterator::operator++() {
325 // If we're at the end and the previous char was a '/', return '.' unless
326 // we are the root path.
327 size_t root_dir_pos = root_dir_start(Path);
328 if (Position == Path.size() &&
329 Path.size() > root_dir_pos + 1 &&
330 is_separator(Path[Position - 1])) {
336 // Skip separators unless it's the root directory.
337 size_t end_pos = Position;
340 (end_pos - 1) != root_dir_pos &&
341 is_separator(Path[end_pos - 1]))
344 // Find next separator.
345 size_t start_pos = filename_pos(Path.substr(0, end_pos));
346 Component = Path.slice(start_pos, end_pos);
347 Position = start_pos;
351 bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
352 return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
353 Position == RHS.Position;
356 ptrdiff_t reverse_iterator::operator-(const reverse_iterator &RHS) const {
357 return Position - RHS.Position;
360 StringRef root_path(StringRef path) {
361 const_iterator b = begin(path),
365 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
373 if (has_net || has_drive) {
374 if ((++pos != e) && is_separator((*pos)[0])) {
375 // {C:/,//net/}, so get the first two components.
376 return path.substr(0, b->size() + pos->size());
378 // just {C:,//net}, return the first component.
383 // POSIX style root directory.
384 if (is_separator((*b)[0])) {
392 StringRef root_name(StringRef path) {
393 const_iterator b = begin(path),
396 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
404 if (has_net || has_drive) {
405 // just {C:,//net}, return the first component.
410 // No path or no name.
414 StringRef root_directory(StringRef path) {
415 const_iterator b = begin(path),
419 bool has_net = b->size() > 2 && is_separator((*b)[0]) && (*b)[1] == (*b)[0];
427 if ((has_net || has_drive) &&
428 // {C:,//net}, skip to the next component.
429 (++pos != e) && is_separator((*pos)[0])) {
433 // POSIX style root directory.
434 if (!has_net && is_separator((*b)[0])) {
439 // No path or no root.
443 StringRef relative_path(StringRef path) {
444 StringRef root = root_path(path);
445 return path.substr(root.size());
448 void append(SmallVectorImpl<char> &path, const Twine &a,
452 SmallString<32> a_storage;
453 SmallString<32> b_storage;
454 SmallString<32> c_storage;
455 SmallString<32> d_storage;
457 SmallVector<StringRef, 4> components;
458 if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
459 if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
460 if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
461 if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
463 for (auto &component : components) {
464 bool path_has_sep = !path.empty() && is_separator(path[path.size() - 1]);
465 bool component_has_sep = !component.empty() && is_separator(component[0]);
466 bool is_root_name = has_root_name(component);
469 // Strip separators from beginning of component.
470 size_t loc = component.find_first_not_of(separators);
471 StringRef c = component.substr(loc);
474 path.append(c.begin(), c.end());
478 if (!component_has_sep && !(path.empty() || is_root_name)) {
480 path.push_back(preferred_separator);
483 path.append(component.begin(), component.end());
487 void append(SmallVectorImpl<char> &path,
488 const_iterator begin, const_iterator end) {
489 for (; begin != end; ++begin)
490 path::append(path, *begin);
493 StringRef parent_path(StringRef path) {
494 size_t end_pos = parent_path_end(path);
495 if (end_pos == StringRef::npos)
498 return path.substr(0, end_pos);
501 void remove_filename(SmallVectorImpl<char> &path) {
502 size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()));
503 if (end_pos != StringRef::npos)
504 path.set_size(end_pos);
507 void replace_extension(SmallVectorImpl<char> &path, const Twine &extension) {
508 StringRef p(path.begin(), path.size());
509 SmallString<32> ext_storage;
510 StringRef ext = extension.toStringRef(ext_storage);
512 // Erase existing extension.
513 size_t pos = p.find_last_of('.');
514 if (pos != StringRef::npos && pos >= filename_pos(p))
517 // Append '.' if needed.
518 if (ext.size() > 0 && ext[0] != '.')
522 path.append(ext.begin(), ext.end());
525 void replace_path_prefix(SmallVectorImpl<char> &Path,
526 const StringRef &OldPrefix,
527 const StringRef &NewPrefix) {
528 if (OldPrefix.empty() && NewPrefix.empty())
531 StringRef OrigPath(Path.begin(), Path.size());
532 if (!OrigPath.startswith(OldPrefix))
535 // If prefixes have the same size we can simply copy the new one over.
536 if (OldPrefix.size() == NewPrefix.size()) {
537 std::copy(NewPrefix.begin(), NewPrefix.end(), Path.begin());
541 StringRef RelPath = OrigPath.substr(OldPrefix.size());
542 SmallString<256> NewPath;
543 path::append(NewPath, NewPrefix);
544 path::append(NewPath, RelPath);
548 void native(const Twine &path, SmallVectorImpl<char> &result) {
549 assert((!path.isSingleStringRef() ||
550 path.getSingleStringRef().data() != result.data()) &&
551 "path and result are not allowed to overlap!");
554 path.toVector(result);
558 void native(SmallVectorImpl<char> &Path) {
562 std::replace(Path.begin(), Path.end(), '/', '\\');
563 if (Path[0] == '~' && (Path.size() == 1 || is_separator(Path[1]))) {
564 SmallString<128> PathHome;
565 home_directory(PathHome);
566 PathHome.append(Path.begin() + 1, Path.end());
570 for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
573 if (PN < PE && *PN == '\\')
574 ++PI; // increment once, the for loop will move over the escaped slash
582 std::string convert_to_slash(StringRef path) {
584 std::string s = path.str();
585 std::replace(s.begin(), s.end(), '\\', '/');
592 StringRef filename(StringRef path) {
593 return *rbegin(path);
596 StringRef stem(StringRef path) {
597 StringRef fname = filename(path);
598 size_t pos = fname.find_last_of('.');
599 if (pos == StringRef::npos)
602 if ((fname.size() == 1 && fname == ".") ||
603 (fname.size() == 2 && fname == ".."))
606 return fname.substr(0, pos);
609 StringRef extension(StringRef path) {
610 StringRef fname = filename(path);
611 size_t pos = fname.find_last_of('.');
612 if (pos == StringRef::npos)
615 if ((fname.size() == 1 && fname == ".") ||
616 (fname.size() == 2 && fname == ".."))
619 return fname.substr(pos);
622 bool is_separator(char value) {
625 case '\\': // fall through
627 case '/': return true;
628 default: return false;
632 static const char preferred_separator_string[] = { preferred_separator, '\0' };
634 StringRef get_separator() {
635 return preferred_separator_string;
638 bool has_root_name(const Twine &path) {
639 SmallString<128> path_storage;
640 StringRef p = path.toStringRef(path_storage);
642 return !root_name(p).empty();
645 bool has_root_directory(const Twine &path) {
646 SmallString<128> path_storage;
647 StringRef p = path.toStringRef(path_storage);
649 return !root_directory(p).empty();
652 bool has_root_path(const Twine &path) {
653 SmallString<128> path_storage;
654 StringRef p = path.toStringRef(path_storage);
656 return !root_path(p).empty();
659 bool has_relative_path(const Twine &path) {
660 SmallString<128> path_storage;
661 StringRef p = path.toStringRef(path_storage);
663 return !relative_path(p).empty();
666 bool has_filename(const Twine &path) {
667 SmallString<128> path_storage;
668 StringRef p = path.toStringRef(path_storage);
670 return !filename(p).empty();
673 bool has_parent_path(const Twine &path) {
674 SmallString<128> path_storage;
675 StringRef p = path.toStringRef(path_storage);
677 return !parent_path(p).empty();
680 bool has_stem(const Twine &path) {
681 SmallString<128> path_storage;
682 StringRef p = path.toStringRef(path_storage);
684 return !stem(p).empty();
687 bool has_extension(const Twine &path) {
688 SmallString<128> path_storage;
689 StringRef p = path.toStringRef(path_storage);
691 return !extension(p).empty();
694 bool is_absolute(const Twine &path) {
695 SmallString<128> path_storage;
696 StringRef p = path.toStringRef(path_storage);
698 bool rootDir = has_root_directory(p),
700 rootName = has_root_name(p);
705 return rootDir && rootName;
708 bool is_relative(const Twine &path) { return !is_absolute(path); }
710 StringRef remove_leading_dotslash(StringRef Path) {
711 // Remove leading "./" (or ".//" or "././" etc.)
712 while (Path.size() > 2 && Path[0] == '.' && is_separator(Path[1])) {
713 Path = Path.substr(2);
714 while (Path.size() > 0 && is_separator(Path[0]))
715 Path = Path.substr(1);
720 static SmallString<256> remove_dots(StringRef path, bool remove_dot_dot) {
721 SmallVector<StringRef, 16> components;
723 // Skip the root path, then look for traversal in the components.
724 StringRef rel = path::relative_path(path);
725 for (StringRef C : llvm::make_range(path::begin(rel), path::end(rel))) {
728 // Leading ".." will remain in the path unless it's at the root.
729 if (remove_dot_dot && C == "..") {
730 if (!components.empty() && components.back() != "..") {
731 components.pop_back();
734 if (path::is_absolute(path))
737 components.push_back(C);
740 SmallString<256> buffer = path::root_path(path);
741 for (StringRef C : components)
742 path::append(buffer, C);
746 bool remove_dots(SmallVectorImpl<char> &path, bool remove_dot_dot) {
747 StringRef p(path.data(), path.size());
749 SmallString<256> result = remove_dots(p, remove_dot_dot);
757 } // end namespace path
761 std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
763 std::error_code EC = status(Path, Status);
766 Result = Status.getUniqueID();
767 return std::error_code();
770 std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
771 SmallVectorImpl<char> &ResultPath,
773 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
776 std::error_code createUniqueFile(const Twine &Model,
777 SmallVectorImpl<char> &ResultPath) {
779 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
782 static std::error_code
783 createTemporaryFile(const Twine &Model, int &ResultFD,
784 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
785 SmallString<128> Storage;
786 StringRef P = Model.toNullTerminatedStringRef(Storage);
787 assert(P.find_first_of(separators) == StringRef::npos &&
788 "Model must be a simple filename.");
789 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
790 return createUniqueEntity(P.begin(), ResultFD, ResultPath,
791 true, owner_read | owner_write, Type);
794 static std::error_code
795 createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
796 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
797 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
798 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
802 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
804 SmallVectorImpl<char> &ResultPath) {
805 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
808 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
809 SmallVectorImpl<char> &ResultPath) {
811 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
815 // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
816 // for consistency. We should try using mkdtemp.
817 std::error_code createUniqueDirectory(const Twine &Prefix,
818 SmallVectorImpl<char> &ResultPath) {
820 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
824 static std::error_code make_absolute(const Twine ¤t_directory,
825 SmallVectorImpl<char> &path,
826 bool use_current_directory) {
827 StringRef p(path.data(), path.size());
829 bool rootDirectory = path::has_root_directory(p),
831 rootName = path::has_root_name(p);
837 if (rootName && rootDirectory)
838 return std::error_code();
840 // All of the following conditions will need the current directory.
841 SmallString<128> current_dir;
842 if (use_current_directory)
843 current_directory.toVector(current_dir);
844 else if (std::error_code ec = current_path(current_dir))
847 // Relative path. Prepend the current directory.
848 if (!rootName && !rootDirectory) {
849 // Append path to the current directory.
850 path::append(current_dir, p);
851 // Set path to the result.
852 path.swap(current_dir);
853 return std::error_code();
856 if (!rootName && rootDirectory) {
857 StringRef cdrn = path::root_name(current_dir);
858 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
859 path::append(curDirRootName, p);
860 // Set path to the result.
861 path.swap(curDirRootName);
862 return std::error_code();
865 if (rootName && !rootDirectory) {
866 StringRef pRootName = path::root_name(p);
867 StringRef bRootDirectory = path::root_directory(current_dir);
868 StringRef bRelativePath = path::relative_path(current_dir);
869 StringRef pRelativePath = path::relative_path(p);
871 SmallString<128> res;
872 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
874 return std::error_code();
877 llvm_unreachable("All rootName and rootDirectory combinations should have "
881 std::error_code make_absolute(const Twine ¤t_directory,
882 SmallVectorImpl<char> &path) {
883 return make_absolute(current_directory, path, true);
886 std::error_code make_absolute(SmallVectorImpl<char> &path) {
887 return make_absolute(Twine(), path, false);
890 std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
892 SmallString<128> PathStorage;
893 StringRef P = Path.toStringRef(PathStorage);
895 // Be optimistic and try to create the directory
896 std::error_code EC = create_directory(P, IgnoreExisting, Perms);
897 // If we succeeded, or had any error other than the parent not existing, just
899 if (EC != errc::no_such_file_or_directory)
902 // We failed because of a no_such_file_or_directory, try to create the
904 StringRef Parent = path::parent_path(P);
908 if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
911 return create_directory(P, IgnoreExisting, Perms);
914 std::error_code copy_file(const Twine &From, const Twine &To) {
916 if (std::error_code EC = openFileForRead(From, ReadFD))
918 if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
923 const size_t BufSize = 4096;
924 char *Buf = new char[BufSize];
925 int BytesRead = 0, BytesWritten = 0;
927 BytesRead = read(ReadFD, Buf, BufSize);
931 BytesWritten = write(WriteFD, Buf, BytesRead);
932 if (BytesWritten < 0)
934 BytesRead -= BytesWritten;
936 if (BytesWritten < 0)
943 if (BytesRead < 0 || BytesWritten < 0)
944 return std::error_code(errno, std::generic_category());
945 return std::error_code();
948 bool exists(file_status status) {
949 return status_known(status) && status.type() != file_type::file_not_found;
952 bool status_known(file_status s) {
953 return s.type() != file_type::status_error;
956 file_type get_file_type(const Twine &Path, bool Follow) {
958 if (status(Path, st, Follow))
959 return file_type::status_error;
963 bool is_directory(file_status status) {
964 return status.type() == file_type::directory_file;
967 std::error_code is_directory(const Twine &path, bool &result) {
969 if (std::error_code ec = status(path, st))
971 result = is_directory(st);
972 return std::error_code();
975 bool is_regular_file(file_status status) {
976 return status.type() == file_type::regular_file;
979 std::error_code is_regular_file(const Twine &path, bool &result) {
981 if (std::error_code ec = status(path, st))
983 result = is_regular_file(st);
984 return std::error_code();
987 bool is_symlink_file(file_status status) {
988 return status.type() == file_type::symlink_file;
991 std::error_code is_symlink_file(const Twine &path, bool &result) {
993 if (std::error_code ec = status(path, st, false))
995 result = is_symlink_file(st);
996 return std::error_code();
999 bool is_other(file_status status) {
1000 return exists(status) &&
1001 !is_regular_file(status) &&
1002 !is_directory(status);
1005 std::error_code is_other(const Twine &Path, bool &Result) {
1006 file_status FileStatus;
1007 if (std::error_code EC = status(Path, FileStatus))
1009 Result = is_other(FileStatus);
1010 return std::error_code();
1013 void directory_entry::replace_filename(const Twine &filename, file_status st) {
1014 SmallString<128> path = path::parent_path(Path);
1015 path::append(path, filename);
1021 static bool startswith(StringRef Magic, const char (&S)[N]) {
1022 return Magic.startswith(StringRef(S, N - 1));
1025 /// @brief Identify the magic in magic.
1026 file_magic identify_magic(StringRef Magic) {
1027 if (Magic.size() < 4)
1028 return file_magic::unknown;
1029 switch ((unsigned char)Magic[0]) {
1031 // COFF bigobj, CL.exe's LTO object file, or short import library file
1032 if (startswith(Magic, "\0\0\xFF\xFF")) {
1033 size_t MinSize = offsetof(COFF::BigObjHeader, UUID) + sizeof(COFF::BigObjMagic);
1034 if (Magic.size() < MinSize)
1035 return file_magic::coff_import_library;
1037 const char *Start = Magic.data() + offsetof(COFF::BigObjHeader, UUID);
1038 if (memcmp(Start, COFF::BigObjMagic, sizeof(COFF::BigObjMagic)) == 0)
1039 return file_magic::coff_object;
1040 if (memcmp(Start, COFF::ClGlObjMagic, sizeof(COFF::BigObjMagic)) == 0)
1041 return file_magic::coff_cl_gl_object;
1042 return file_magic::coff_import_library;
1044 // Windows resource file
1045 if (startswith(Magic, "\0\0\0\0\x20\0\0\0\xFF"))
1046 return file_magic::windows_resource;
1047 // 0x0000 = COFF unknown machine type
1049 return file_magic::coff_object;
1050 if (startswith(Magic, "\0asm"))
1051 return file_magic::wasm_object;
1054 case 0xDE: // 0x0B17C0DE = BC wraper
1055 if (startswith(Magic, "\xDE\xC0\x17\x0B"))
1056 return file_magic::bitcode;
1059 if (startswith(Magic, "BC\xC0\xDE"))
1060 return file_magic::bitcode;
1063 if (startswith(Magic, "!<arch>\n") || startswith(Magic, "!<thin>\n"))
1064 return file_magic::archive;
1068 if (startswith(Magic, "\177ELF") && Magic.size() >= 18) {
1069 bool Data2MSB = Magic[5] == 2;
1070 unsigned high = Data2MSB ? 16 : 17;
1071 unsigned low = Data2MSB ? 17 : 16;
1072 if (Magic[high] == 0) {
1073 switch (Magic[low]) {
1074 default: return file_magic::elf;
1075 case 1: return file_magic::elf_relocatable;
1076 case 2: return file_magic::elf_executable;
1077 case 3: return file_magic::elf_shared_object;
1078 case 4: return file_magic::elf_core;
1081 // It's still some type of ELF file.
1082 return file_magic::elf;
1087 if (startswith(Magic, "\xCA\xFE\xBA\xBE") ||
1088 startswith(Magic, "\xCA\xFE\xBA\xBF")) {
1089 // This is complicated by an overlap with Java class files.
1090 // See the Mach-O section in /usr/share/file/magic for details.
1091 if (Magic.size() >= 8 && Magic[7] < 43)
1092 return file_magic::macho_universal_binary;
1096 // The two magic numbers for mach-o are:
1097 // 0xfeedface - 32-bit mach-o
1098 // 0xfeedfacf - 64-bit mach-o
1103 if (startswith(Magic, "\xFE\xED\xFA\xCE") ||
1104 startswith(Magic, "\xFE\xED\xFA\xCF")) {
1107 if (Magic[3] == char(0xCE))
1108 MinSize = sizeof(MachO::mach_header);
1110 MinSize = sizeof(MachO::mach_header_64);
1111 if (Magic.size() >= MinSize)
1112 type = Magic[12] << 24 | Magic[13] << 12 | Magic[14] << 8 | Magic[15];
1113 } else if (startswith(Magic, "\xCE\xFA\xED\xFE") ||
1114 startswith(Magic, "\xCF\xFA\xED\xFE")) {
1115 /* Reverse endian */
1117 if (Magic[0] == char(0xCE))
1118 MinSize = sizeof(MachO::mach_header);
1120 MinSize = sizeof(MachO::mach_header_64);
1121 if (Magic.size() >= MinSize)
1122 type = Magic[15] << 24 | Magic[14] << 12 |Magic[13] << 8 | Magic[12];
1126 case 1: return file_magic::macho_object;
1127 case 2: return file_magic::macho_executable;
1128 case 3: return file_magic::macho_fixed_virtual_memory_shared_lib;
1129 case 4: return file_magic::macho_core;
1130 case 5: return file_magic::macho_preload_executable;
1131 case 6: return file_magic::macho_dynamically_linked_shared_lib;
1132 case 7: return file_magic::macho_dynamic_linker;
1133 case 8: return file_magic::macho_bundle;
1134 case 9: return file_magic::macho_dynamically_linked_shared_lib_stub;
1135 case 10: return file_magic::macho_dsym_companion;
1136 case 11: return file_magic::macho_kext_bundle;
1140 case 0xF0: // PowerPC Windows
1141 case 0x83: // Alpha 32-bit
1142 case 0x84: // Alpha 64-bit
1143 case 0x66: // MPS R4000 Windows
1145 case 0x4c: // 80386 Windows
1146 case 0xc4: // ARMNT Windows
1147 if (Magic[1] == 0x01)
1148 return file_magic::coff_object;
1150 case 0x90: // PA-RISC Windows
1151 case 0x68: // mc68K Windows
1152 if (Magic[1] == 0x02)
1153 return file_magic::coff_object;
1156 case 'M': // Possible MS-DOS stub on Windows PE file
1157 if (startswith(Magic, "MZ")) {
1158 uint32_t off = read32le(Magic.data() + 0x3c);
1159 // PE/COFF file, either EXE or DLL.
1160 if (off < Magic.size() &&
1161 memcmp(Magic.data()+off, COFF::PEMagic, sizeof(COFF::PEMagic)) == 0)
1162 return file_magic::pecoff_executable;
1166 case 0x64: // x86-64 Windows.
1167 if (Magic[1] == char(0x86))
1168 return file_magic::coff_object;
1174 return file_magic::unknown;
1177 std::error_code identify_magic(const Twine &Path, file_magic &Result) {
1179 if (std::error_code EC = openFileForRead(Path, FD))
1183 int Length = read(FD, Buffer, sizeof(Buffer));
1184 if (close(FD) != 0 || Length < 0)
1185 return std::error_code(errno, std::generic_category());
1187 Result = identify_magic(StringRef(Buffer, Length));
1188 return std::error_code();
1191 std::error_code directory_entry::status(file_status &result) const {
1192 return fs::status(Path, result, FollowSymlinks);
\r
1195 ErrorOr<perms> getPermissions(const Twine &Path) {
\r
1196 file_status Status;
\r
1197 if (std::error_code EC = status(Path, Status))
\r
1200 return Status.permissions();
\r
1203 } // end namespace fs
\r
1204 } // end namespace sys
\r
1205 } // end namespace llvm
\r
1207 // Include the truly platform-specific parts.
1208 #if defined(LLVM_ON_UNIX)
1209 #include "Unix/Path.inc"
1211 #if defined(LLVM_ON_WIN32)
1212 #include "Windows/Path.inc"
1219 bool user_cache_directory(SmallVectorImpl<char> &Result, const Twine &Path1,
1220 const Twine &Path2, const Twine &Path3) {
1221 if (getUserCacheDir(Result)) {
1222 append(Result, Path1, Path2, Path3);
1228 } // end namespace path
1229 } // end namsspace sys
1230 } // end namespace llvm