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/Path.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/Support/COFF.h"
17 #include "llvm/Support/Endian.h"
18 #include "llvm/Support/Errc.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/MachO.h"
22 #include "llvm/Support/Process.h"
26 #if !defined(_MSC_VER) && !defined(__MINGW32__)
33 using namespace llvm::support::endian;
36 using llvm::StringRef;
37 using llvm::sys::path::is_separator;
38 using llvm::sys::path::Style;
40 inline Style real_style(Style style) {
42 return (style == Style::posix) ? Style::posix : Style::windows;
44 return (style == Style::windows) ? Style::windows : Style::posix;
48 inline const char *separators(Style style) {
49 if (real_style(style) == Style::windows)
54 inline char preferred_separator(Style style) {
55 if (real_style(style) == Style::windows)
60 StringRef find_first_component(StringRef path, Style style) {
61 // Look for this first component in the following order.
62 // * empty (in this case we return an empty string)
63 // * either C: or {//,\\}net.
65 // * {file,directory}name
70 if (real_style(style) == Style::windows) {
72 if (path.size() >= 2 &&
73 std::isalpha(static_cast<unsigned char>(path[0])) && path[1] == ':')
74 return path.substr(0, 2);
78 if ((path.size() > 2) && is_separator(path[0], style) &&
79 path[0] == path[1] && !is_separator(path[2], style)) {
80 // Find the next directory separator.
81 size_t end = path.find_first_of(separators(style), 2);
82 return path.substr(0, end);
86 if (is_separator(path[0], style))
87 return path.substr(0, 1);
89 // * {file,directory}name
90 size_t end = path.find_first_of(separators(style));
91 return path.substr(0, end);
94 size_t filename_pos(StringRef str, Style style) {
95 if (str.size() == 2 && is_separator(str[0], style) && str[0] == str[1])
98 if (str.size() > 0 && is_separator(str[str.size() - 1], style))
99 return str.size() - 1;
101 size_t pos = str.find_last_of(separators(style), str.size() - 1);
103 if (real_style(style) == Style::windows) {
104 if (pos == StringRef::npos)
105 pos = str.find_last_of(':', str.size() - 2);
108 if (pos == StringRef::npos || (pos == 1 && is_separator(str[0], style)))
114 size_t root_dir_start(StringRef str, Style style) {
116 if (real_style(style) == Style::windows) {
117 if (str.size() > 2 && str[1] == ':' && is_separator(str[2], style))
122 if (str.size() == 2 && is_separator(str[0], style) && str[0] == str[1])
123 return StringRef::npos;
126 if (str.size() > 3 && is_separator(str[0], style) && str[0] == str[1] &&
127 !is_separator(str[2], style)) {
128 return str.find_first_of(separators(style), 2);
132 if (str.size() > 0 && is_separator(str[0], style))
135 return StringRef::npos;
138 size_t parent_path_end(StringRef path, Style style) {
139 size_t end_pos = filename_pos(path, style);
141 bool filename_was_sep =
142 path.size() > 0 && is_separator(path[end_pos], style);
144 // Skip separators except for root dir.
145 size_t root_dir_pos = root_dir_start(path.substr(0, end_pos), style);
147 while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
148 is_separator(path[end_pos - 1], style))
151 if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep)
152 return StringRef::npos;
156 } // end unnamed namespace
164 static std::error_code createUniqueEntity(const Twine &Model, int &ResultFD,
165 SmallVectorImpl<char> &ResultPath,
166 bool MakeAbsolute, unsigned Mode,
168 SmallString<128> ModelStorage;
169 Model.toVector(ModelStorage);
172 // Make model absolute by prepending a temp directory if it's not already.
173 if (!sys::path::is_absolute(Twine(ModelStorage))) {
174 SmallString<128> TDir;
175 sys::path::system_temp_directory(true, TDir);
176 sys::path::append(TDir, Twine(ModelStorage));
177 ModelStorage.swap(TDir);
181 // From here on, DO NOT modify model. It may be needed if the randomly chosen
182 // path already exists.
183 ResultPath = ModelStorage;
185 ResultPath.push_back(0);
186 ResultPath.pop_back();
189 // Replace '%' with random chars.
190 for (unsigned i = 0, e = ModelStorage.size(); i != e; ++i) {
191 if (ModelStorage[i] == '%')
192 ResultPath[i] = "0123456789abcdef"[sys::Process::GetRandomNumber() & 15];
195 // Try to open + create the file.
198 if (std::error_code EC =
199 sys::fs::openFileForWrite(Twine(ResultPath.begin()), ResultFD,
200 sys::fs::F_RW | sys::fs::F_Excl, Mode)) {
201 if (EC == errc::file_exists)
202 goto retry_random_path;
206 return std::error_code();
211 sys::fs::access(ResultPath.begin(), sys::fs::AccessMode::Exist);
212 if (EC == errc::no_such_file_or_directory)
213 return std::error_code();
216 goto retry_random_path;
220 if (std::error_code EC =
221 sys::fs::create_directory(ResultPath.begin(), false)) {
222 if (EC == errc::file_exists)
223 goto retry_random_path;
226 return std::error_code();
229 llvm_unreachable("Invalid Type");
236 const_iterator begin(StringRef path, Style style) {
239 i.Component = find_first_component(path, style);
245 const_iterator end(StringRef path) {
248 i.Position = path.size();
252 const_iterator &const_iterator::operator++() {
253 assert(Position < Path.size() && "Tried to increment past end!");
255 // Increment Position to past the current component
256 Position += Component.size();
259 if (Position == Path.size()) {
260 Component = StringRef();
264 // Both POSIX and Windows treat paths that begin with exactly two separators
266 bool was_net = Component.size() > 2 && is_separator(Component[0], S) &&
267 Component[1] == Component[0] && !is_separator(Component[2], S);
269 // Handle separators.
270 if (is_separator(Path[Position], S)) {
274 (real_style(S) == Style::windows && Component.endswith(":"))) {
275 Component = Path.substr(Position, 1);
279 // Skip extra separators.
280 while (Position != Path.size() && is_separator(Path[Position], S)) {
284 // Treat trailing '/' as a '.'.
285 if (Position == Path.size()) {
292 // Find next component.
293 size_t end_pos = Path.find_first_of(separators(S), Position);
294 Component = Path.slice(Position, end_pos);
299 bool const_iterator::operator==(const const_iterator &RHS) const {
300 return Path.begin() == RHS.Path.begin() && Position == RHS.Position;
303 ptrdiff_t const_iterator::operator-(const const_iterator &RHS) const {
304 return Position - RHS.Position;
307 reverse_iterator rbegin(StringRef Path, Style style) {
310 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, S);
327 if (Position == Path.size() && Path.size() > root_dir_pos + 1 &&
328 is_separator(Path[Position - 1], S)) {
334 // Skip separators unless it's the root directory.
335 size_t end_pos = Position;
337 while (end_pos > 0 && (end_pos - 1) != root_dir_pos &&
338 is_separator(Path[end_pos - 1], S))
341 // Find next separator.
342 size_t start_pos = filename_pos(Path.substr(0, end_pos), S);
343 Component = Path.slice(start_pos, end_pos);
344 Position = start_pos;
348 bool reverse_iterator::operator==(const reverse_iterator &RHS) const {
349 return Path.begin() == RHS.Path.begin() && Component == RHS.Component &&
350 Position == RHS.Position;
353 ptrdiff_t reverse_iterator::operator-(const reverse_iterator &RHS) const {
354 return Position - RHS.Position;
357 StringRef root_path(StringRef path, Style style) {
358 const_iterator b = begin(path, style), pos = b, e = end(path);
361 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
362 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
364 if (has_net || has_drive) {
365 if ((++pos != e) && is_separator((*pos)[0], style)) {
366 // {C:/,//net/}, so get the first two components.
367 return path.substr(0, b->size() + pos->size());
369 // just {C:,//net}, return the first component.
374 // POSIX style root directory.
375 if (is_separator((*b)[0], style)) {
383 StringRef root_name(StringRef path, Style style) {
384 const_iterator b = begin(path, style), e = end(path);
387 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
388 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
390 if (has_net || has_drive) {
391 // just {C:,//net}, return the first component.
396 // No path or no name.
400 StringRef root_directory(StringRef path, Style style) {
401 const_iterator b = begin(path, style), pos = b, e = end(path);
404 b->size() > 2 && is_separator((*b)[0], style) && (*b)[1] == (*b)[0];
405 bool has_drive = (real_style(style) == Style::windows) && b->endswith(":");
407 if ((has_net || has_drive) &&
408 // {C:,//net}, skip to the next component.
409 (++pos != e) && is_separator((*pos)[0], style)) {
413 // POSIX style root directory.
414 if (!has_net && is_separator((*b)[0], style)) {
419 // No path or no root.
423 StringRef relative_path(StringRef path, Style style) {
424 StringRef root = root_path(path, style);
425 return path.substr(root.size());
428 void append(SmallVectorImpl<char> &path, Style style, const Twine &a,
429 const Twine &b, const Twine &c, const Twine &d) {
430 SmallString<32> a_storage;
431 SmallString<32> b_storage;
432 SmallString<32> c_storage;
433 SmallString<32> d_storage;
435 SmallVector<StringRef, 4> components;
436 if (!a.isTriviallyEmpty()) components.push_back(a.toStringRef(a_storage));
437 if (!b.isTriviallyEmpty()) components.push_back(b.toStringRef(b_storage));
438 if (!c.isTriviallyEmpty()) components.push_back(c.toStringRef(c_storage));
439 if (!d.isTriviallyEmpty()) components.push_back(d.toStringRef(d_storage));
441 for (auto &component : components) {
443 !path.empty() && is_separator(path[path.size() - 1], style);
444 bool component_has_sep =
445 !component.empty() && is_separator(component[0], style);
446 bool is_root_name = has_root_name(component, style);
449 // Strip separators from beginning of component.
450 size_t loc = component.find_first_not_of(separators(style));
451 StringRef c = component.substr(loc);
454 path.append(c.begin(), c.end());
458 if (!component_has_sep && !(path.empty() || is_root_name)) {
460 path.push_back(preferred_separator(style));
463 path.append(component.begin(), component.end());
467 void append(SmallVectorImpl<char> &path, const Twine &a, const Twine &b,
468 const Twine &c, const Twine &d) {
469 append(path, Style::native, a, b, c, d);
472 void append(SmallVectorImpl<char> &path, const_iterator begin,
473 const_iterator end, Style style) {
474 for (; begin != end; ++begin)
475 path::append(path, style, *begin);
478 StringRef parent_path(StringRef path, Style style) {
479 size_t end_pos = parent_path_end(path, style);
480 if (end_pos == StringRef::npos)
483 return path.substr(0, end_pos);
486 void remove_filename(SmallVectorImpl<char> &path, Style style) {
487 size_t end_pos = parent_path_end(StringRef(path.begin(), path.size()), style);
488 if (end_pos != StringRef::npos)
489 path.set_size(end_pos);
492 void replace_extension(SmallVectorImpl<char> &path, const Twine &extension,
494 StringRef p(path.begin(), path.size());
495 SmallString<32> ext_storage;
496 StringRef ext = extension.toStringRef(ext_storage);
498 // Erase existing extension.
499 size_t pos = p.find_last_of('.');
500 if (pos != StringRef::npos && pos >= filename_pos(p, style))
503 // Append '.' if needed.
504 if (ext.size() > 0 && ext[0] != '.')
508 path.append(ext.begin(), ext.end());
511 void replace_path_prefix(SmallVectorImpl<char> &Path,
512 const StringRef &OldPrefix, const StringRef &NewPrefix,
514 if (OldPrefix.empty() && NewPrefix.empty())
517 StringRef OrigPath(Path.begin(), Path.size());
518 if (!OrigPath.startswith(OldPrefix))
521 // If prefixes have the same size we can simply copy the new one over.
522 if (OldPrefix.size() == NewPrefix.size()) {
523 std::copy(NewPrefix.begin(), NewPrefix.end(), Path.begin());
527 StringRef RelPath = OrigPath.substr(OldPrefix.size());
528 SmallString<256> NewPath;
529 path::append(NewPath, style, NewPrefix);
530 path::append(NewPath, style, RelPath);
534 void native(const Twine &path, SmallVectorImpl<char> &result, Style style) {
535 assert((!path.isSingleStringRef() ||
536 path.getSingleStringRef().data() != result.data()) &&
537 "path and result are not allowed to overlap!");
540 path.toVector(result);
541 native(result, style);
544 void native(SmallVectorImpl<char> &Path, Style style) {
547 if (real_style(style) == Style::windows) {
548 std::replace(Path.begin(), Path.end(), '/', '\\');
549 if (Path[0] == '~' && (Path.size() == 1 || is_separator(Path[1], style))) {
550 SmallString<128> PathHome;
551 home_directory(PathHome);
552 PathHome.append(Path.begin() + 1, Path.end());
556 for (auto PI = Path.begin(), PE = Path.end(); PI < PE; ++PI) {
559 if (PN < PE && *PN == '\\')
560 ++PI; // increment once, the for loop will move over the escaped slash
568 std::string convert_to_slash(StringRef path, Style style) {
569 if (real_style(style) != Style::windows)
572 std::string s = path.str();
573 std::replace(s.begin(), s.end(), '\\', '/');
577 StringRef filename(StringRef path, Style style) { return *rbegin(path, style); }
579 StringRef stem(StringRef path, Style style) {
580 StringRef fname = filename(path, style);
581 size_t pos = fname.find_last_of('.');
582 if (pos == StringRef::npos)
585 if ((fname.size() == 1 && fname == ".") ||
586 (fname.size() == 2 && fname == ".."))
589 return fname.substr(0, pos);
592 StringRef extension(StringRef path, Style style) {
593 StringRef fname = filename(path, style);
594 size_t pos = fname.find_last_of('.');
595 if (pos == StringRef::npos)
598 if ((fname.size() == 1 && fname == ".") ||
599 (fname.size() == 2 && fname == ".."))
602 return fname.substr(pos);
605 bool is_separator(char value, Style style) {
608 if (real_style(style) == Style::windows)
609 return value == '\\';
613 StringRef get_separator(Style style) {
614 if (real_style(style) == Style::windows)
619 bool has_root_name(const Twine &path, Style style) {
620 SmallString<128> path_storage;
621 StringRef p = path.toStringRef(path_storage);
623 return !root_name(p, style).empty();
626 bool has_root_directory(const Twine &path, Style style) {
627 SmallString<128> path_storage;
628 StringRef p = path.toStringRef(path_storage);
630 return !root_directory(p, style).empty();
633 bool has_root_path(const Twine &path, Style style) {
634 SmallString<128> path_storage;
635 StringRef p = path.toStringRef(path_storage);
637 return !root_path(p, style).empty();
640 bool has_relative_path(const Twine &path, Style style) {
641 SmallString<128> path_storage;
642 StringRef p = path.toStringRef(path_storage);
644 return !relative_path(p, style).empty();
647 bool has_filename(const Twine &path, Style style) {
648 SmallString<128> path_storage;
649 StringRef p = path.toStringRef(path_storage);
651 return !filename(p, style).empty();
654 bool has_parent_path(const Twine &path, Style style) {
655 SmallString<128> path_storage;
656 StringRef p = path.toStringRef(path_storage);
658 return !parent_path(p, style).empty();
661 bool has_stem(const Twine &path, Style style) {
662 SmallString<128> path_storage;
663 StringRef p = path.toStringRef(path_storage);
665 return !stem(p, style).empty();
668 bool has_extension(const Twine &path, Style style) {
669 SmallString<128> path_storage;
670 StringRef p = path.toStringRef(path_storage);
672 return !extension(p, style).empty();
675 bool is_absolute(const Twine &path, Style style) {
676 SmallString<128> path_storage;
677 StringRef p = path.toStringRef(path_storage);
679 bool rootDir = has_root_directory(p, style);
681 (real_style(style) != Style::windows) || has_root_name(p, style);
683 return rootDir && rootName;
686 bool is_relative(const Twine &path, Style style) {
687 return !is_absolute(path, style);
690 StringRef remove_leading_dotslash(StringRef Path, Style style) {
691 // Remove leading "./" (or ".//" or "././" etc.)
692 while (Path.size() > 2 && Path[0] == '.' && is_separator(Path[1], style)) {
693 Path = Path.substr(2);
694 while (Path.size() > 0 && is_separator(Path[0], style))
695 Path = Path.substr(1);
700 static SmallString<256> remove_dots(StringRef path, bool remove_dot_dot,
702 SmallVector<StringRef, 16> components;
704 // Skip the root path, then look for traversal in the components.
705 StringRef rel = path::relative_path(path, style);
707 llvm::make_range(path::begin(rel, style), path::end(rel))) {
710 // Leading ".." will remain in the path unless it's at the root.
711 if (remove_dot_dot && C == "..") {
712 if (!components.empty() && components.back() != "..") {
713 components.pop_back();
716 if (path::is_absolute(path, style))
719 components.push_back(C);
722 SmallString<256> buffer = path::root_path(path, style);
723 for (StringRef C : components)
724 path::append(buffer, style, C);
728 bool remove_dots(SmallVectorImpl<char> &path, bool remove_dot_dot,
730 StringRef p(path.data(), path.size());
732 SmallString<256> result = remove_dots(p, remove_dot_dot, style);
740 } // end namespace path
744 std::error_code getUniqueID(const Twine Path, UniqueID &Result) {
746 std::error_code EC = status(Path, Status);
749 Result = Status.getUniqueID();
750 return std::error_code();
753 std::error_code createUniqueFile(const Twine &Model, int &ResultFd,
754 SmallVectorImpl<char> &ResultPath,
756 return createUniqueEntity(Model, ResultFd, ResultPath, false, Mode, FS_File);
759 std::error_code createUniqueFile(const Twine &Model,
760 SmallVectorImpl<char> &ResultPath) {
762 return createUniqueEntity(Model, Dummy, ResultPath, false, 0, FS_Name);
765 static std::error_code
766 createTemporaryFile(const Twine &Model, int &ResultFD,
767 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
768 SmallString<128> Storage;
769 StringRef P = Model.toNullTerminatedStringRef(Storage);
770 assert(P.find_first_of(separators(Style::native)) == StringRef::npos &&
771 "Model must be a simple filename.");
772 // Use P.begin() so that createUniqueEntity doesn't need to recreate Storage.
773 return createUniqueEntity(P.begin(), ResultFD, ResultPath,
774 true, owner_read | owner_write, Type);
777 static std::error_code
778 createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD,
779 llvm::SmallVectorImpl<char> &ResultPath, FSEntity Type) {
780 const char *Middle = Suffix.empty() ? "-%%%%%%" : "-%%%%%%.";
781 return createTemporaryFile(Prefix + Middle + Suffix, ResultFD, ResultPath,
785 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
787 SmallVectorImpl<char> &ResultPath) {
788 return createTemporaryFile(Prefix, Suffix, ResultFD, ResultPath, FS_File);
791 std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix,
792 SmallVectorImpl<char> &ResultPath) {
794 return createTemporaryFile(Prefix, Suffix, Dummy, ResultPath, FS_Name);
798 // This is a mkdtemp with a different pattern. We use createUniqueEntity mostly
799 // for consistency. We should try using mkdtemp.
800 std::error_code createUniqueDirectory(const Twine &Prefix,
801 SmallVectorImpl<char> &ResultPath) {
803 return createUniqueEntity(Prefix + "-%%%%%%", Dummy, ResultPath,
807 static std::error_code make_absolute(const Twine ¤t_directory,
808 SmallVectorImpl<char> &path,
809 bool use_current_directory) {
810 StringRef p(path.data(), path.size());
812 bool rootDirectory = path::has_root_directory(p);
814 (real_style(Style::native) != Style::windows) || path::has_root_name(p);
817 if (rootName && rootDirectory)
818 return std::error_code();
820 // All of the following conditions will need the current directory.
821 SmallString<128> current_dir;
822 if (use_current_directory)
823 current_directory.toVector(current_dir);
824 else if (std::error_code ec = current_path(current_dir))
827 // Relative path. Prepend the current directory.
828 if (!rootName && !rootDirectory) {
829 // Append path to the current directory.
830 path::append(current_dir, p);
831 // Set path to the result.
832 path.swap(current_dir);
833 return std::error_code();
836 if (!rootName && rootDirectory) {
837 StringRef cdrn = path::root_name(current_dir);
838 SmallString<128> curDirRootName(cdrn.begin(), cdrn.end());
839 path::append(curDirRootName, p);
840 // Set path to the result.
841 path.swap(curDirRootName);
842 return std::error_code();
845 if (rootName && !rootDirectory) {
846 StringRef pRootName = path::root_name(p);
847 StringRef bRootDirectory = path::root_directory(current_dir);
848 StringRef bRelativePath = path::relative_path(current_dir);
849 StringRef pRelativePath = path::relative_path(p);
851 SmallString<128> res;
852 path::append(res, pRootName, bRootDirectory, bRelativePath, pRelativePath);
854 return std::error_code();
857 llvm_unreachable("All rootName and rootDirectory combinations should have "
861 std::error_code make_absolute(const Twine ¤t_directory,
862 SmallVectorImpl<char> &path) {
863 return make_absolute(current_directory, path, true);
866 std::error_code make_absolute(SmallVectorImpl<char> &path) {
867 return make_absolute(Twine(), path, false);
870 std::error_code create_directories(const Twine &Path, bool IgnoreExisting,
872 SmallString<128> PathStorage;
873 StringRef P = Path.toStringRef(PathStorage);
875 // Be optimistic and try to create the directory
876 std::error_code EC = create_directory(P, IgnoreExisting, Perms);
877 // If we succeeded, or had any error other than the parent not existing, just
879 if (EC != errc::no_such_file_or_directory)
882 // We failed because of a no_such_file_or_directory, try to create the
884 StringRef Parent = path::parent_path(P);
888 if ((EC = create_directories(Parent, IgnoreExisting, Perms)))
891 return create_directory(P, IgnoreExisting, Perms);
894 std::error_code copy_file(const Twine &From, const Twine &To) {
896 if (std::error_code EC = openFileForRead(From, ReadFD))
898 if (std::error_code EC = openFileForWrite(To, WriteFD, F_None)) {
903 const size_t BufSize = 4096;
904 char *Buf = new char[BufSize];
905 int BytesRead = 0, BytesWritten = 0;
907 BytesRead = read(ReadFD, Buf, BufSize);
911 BytesWritten = write(WriteFD, Buf, BytesRead);
912 if (BytesWritten < 0)
914 BytesRead -= BytesWritten;
916 if (BytesWritten < 0)
923 if (BytesRead < 0 || BytesWritten < 0)
924 return std::error_code(errno, std::generic_category());
925 return std::error_code();
928 ErrorOr<MD5::MD5Result> md5_contents(int FD) {
931 constexpr size_t BufSize = 4096;
932 std::vector<uint8_t> Buf(BufSize);
935 BytesRead = read(FD, Buf.data(), BufSize);
938 Hash.update(makeArrayRef(Buf.data(), BytesRead));
942 return std::error_code(errno, std::generic_category());
943 MD5::MD5Result Result;
948 ErrorOr<MD5::MD5Result> md5_contents(const Twine &Path) {
950 if (auto EC = openFileForRead(Path, FD))
953 auto Result = md5_contents(FD);
958 bool exists(file_status status) {
959 return status_known(status) && status.type() != file_type::file_not_found;
962 bool status_known(file_status s) {
963 return s.type() != file_type::status_error;
966 file_type get_file_type(const Twine &Path, bool Follow) {
968 if (status(Path, st, Follow))
969 return file_type::status_error;
973 bool is_directory(file_status status) {
974 return status.type() == file_type::directory_file;
977 std::error_code is_directory(const Twine &path, bool &result) {
979 if (std::error_code ec = status(path, st))
981 result = is_directory(st);
982 return std::error_code();
985 bool is_regular_file(file_status status) {
986 return status.type() == file_type::regular_file;
989 std::error_code is_regular_file(const Twine &path, bool &result) {
991 if (std::error_code ec = status(path, st))
993 result = is_regular_file(st);
994 return std::error_code();
997 bool is_symlink_file(file_status status) {
998 return status.type() == file_type::symlink_file;
1001 std::error_code is_symlink_file(const Twine &path, bool &result) {
1003 if (std::error_code ec = status(path, st, false))
1005 result = is_symlink_file(st);
1006 return std::error_code();
1009 bool is_other(file_status status) {
1010 return exists(status) &&
1011 !is_regular_file(status) &&
1012 !is_directory(status);
1015 std::error_code is_other(const Twine &Path, bool &Result) {
1016 file_status FileStatus;
1017 if (std::error_code EC = status(Path, FileStatus))
1019 Result = is_other(FileStatus);
1020 return std::error_code();
1023 void directory_entry::replace_filename(const Twine &filename, file_status st) {
1024 SmallString<128> path = path::parent_path(Path);
1025 path::append(path, filename);
1031 static bool startswith(StringRef Magic, const char (&S)[N]) {
1032 return Magic.startswith(StringRef(S, N - 1));
1035 /// @brief Identify the magic in magic.
1036 file_magic identify_magic(StringRef Magic) {
1037 if (Magic.size() < 4)
1038 return file_magic::unknown;
1039 switch ((unsigned char)Magic[0]) {
1041 // COFF bigobj, CL.exe's LTO object file, or short import library file
1042 if (startswith(Magic, "\0\0\xFF\xFF")) {
1043 size_t MinSize = offsetof(COFF::BigObjHeader, UUID) + sizeof(COFF::BigObjMagic);
1044 if (Magic.size() < MinSize)
1045 return file_magic::coff_import_library;
1047 const char *Start = Magic.data() + offsetof(COFF::BigObjHeader, UUID);
1048 if (memcmp(Start, COFF::BigObjMagic, sizeof(COFF::BigObjMagic)) == 0)
1049 return file_magic::coff_object;
1050 if (memcmp(Start, COFF::ClGlObjMagic, sizeof(COFF::BigObjMagic)) == 0)
1051 return file_magic::coff_cl_gl_object;
1052 return file_magic::coff_import_library;
1054 // Windows resource file
1055 if (startswith(Magic, "\0\0\0\0\x20\0\0\0\xFF"))
1056 return file_magic::windows_resource;
1057 // 0x0000 = COFF unknown machine type
1059 return file_magic::coff_object;
1060 if (startswith(Magic, "\0asm"))
1061 return file_magic::wasm_object;
1064 case 0xDE: // 0x0B17C0DE = BC wraper
1065 if (startswith(Magic, "\xDE\xC0\x17\x0B"))
1066 return file_magic::bitcode;
1069 if (startswith(Magic, "BC\xC0\xDE"))
1070 return file_magic::bitcode;
1073 if (startswith(Magic, "!<arch>\n") || startswith(Magic, "!<thin>\n"))
1074 return file_magic::archive;
1078 if (startswith(Magic, "\177ELF") && Magic.size() >= 18) {
1079 bool Data2MSB = Magic[5] == 2;
1080 unsigned high = Data2MSB ? 16 : 17;
1081 unsigned low = Data2MSB ? 17 : 16;
1082 if (Magic[high] == 0) {
1083 switch (Magic[low]) {
1084 default: return file_magic::elf;
1085 case 1: return file_magic::elf_relocatable;
1086 case 2: return file_magic::elf_executable;
1087 case 3: return file_magic::elf_shared_object;
1088 case 4: return file_magic::elf_core;
1091 // It's still some type of ELF file.
1092 return file_magic::elf;
1097 if (startswith(Magic, "\xCA\xFE\xBA\xBE") ||
1098 startswith(Magic, "\xCA\xFE\xBA\xBF")) {
1099 // This is complicated by an overlap with Java class files.
1100 // See the Mach-O section in /usr/share/file/magic for details.
1101 if (Magic.size() >= 8 && Magic[7] < 43)
1102 return file_magic::macho_universal_binary;
1106 // The two magic numbers for mach-o are:
1107 // 0xfeedface - 32-bit mach-o
1108 // 0xfeedfacf - 64-bit mach-o
1113 if (startswith(Magic, "\xFE\xED\xFA\xCE") ||
1114 startswith(Magic, "\xFE\xED\xFA\xCF")) {
1117 if (Magic[3] == char(0xCE))
1118 MinSize = sizeof(MachO::mach_header);
1120 MinSize = sizeof(MachO::mach_header_64);
1121 if (Magic.size() >= MinSize)
1122 type = Magic[12] << 24 | Magic[13] << 12 | Magic[14] << 8 | Magic[15];
1123 } else if (startswith(Magic, "\xCE\xFA\xED\xFE") ||
1124 startswith(Magic, "\xCF\xFA\xED\xFE")) {
1125 /* Reverse endian */
1127 if (Magic[0] == char(0xCE))
1128 MinSize = sizeof(MachO::mach_header);
1130 MinSize = sizeof(MachO::mach_header_64);
1131 if (Magic.size() >= MinSize)
1132 type = Magic[15] << 24 | Magic[14] << 12 |Magic[13] << 8 | Magic[12];
1136 case 1: return file_magic::macho_object;
1137 case 2: return file_magic::macho_executable;
1138 case 3: return file_magic::macho_fixed_virtual_memory_shared_lib;
1139 case 4: return file_magic::macho_core;
1140 case 5: return file_magic::macho_preload_executable;
1141 case 6: return file_magic::macho_dynamically_linked_shared_lib;
1142 case 7: return file_magic::macho_dynamic_linker;
1143 case 8: return file_magic::macho_bundle;
1144 case 9: return file_magic::macho_dynamically_linked_shared_lib_stub;
1145 case 10: return file_magic::macho_dsym_companion;
1146 case 11: return file_magic::macho_kext_bundle;
1150 case 0xF0: // PowerPC Windows
1151 case 0x83: // Alpha 32-bit
1152 case 0x84: // Alpha 64-bit
1153 case 0x66: // MPS R4000 Windows
1155 case 0x4c: // 80386 Windows
1156 case 0xc4: // ARMNT Windows
1157 if (Magic[1] == 0x01)
1158 return file_magic::coff_object;
1161 case 0x90: // PA-RISC Windows
1162 case 0x68: // mc68K Windows
1163 if (Magic[1] == 0x02)
1164 return file_magic::coff_object;
1167 case 'M': // Possible MS-DOS stub on Windows PE file
1168 if (startswith(Magic, "MZ")) {
1169 uint32_t off = read32le(Magic.data() + 0x3c);
1170 // PE/COFF file, either EXE or DLL.
1171 if (off < Magic.size() &&
1172 memcmp(Magic.data()+off, COFF::PEMagic, sizeof(COFF::PEMagic)) == 0)
1173 return file_magic::pecoff_executable;
1177 case 0x64: // x86-64 Windows.
1178 if (Magic[1] == char(0x86))
1179 return file_magic::coff_object;
1185 return file_magic::unknown;
1188 std::error_code identify_magic(const Twine &Path, file_magic &Result) {
1190 if (std::error_code EC = openFileForRead(Path, FD))
1194 int Length = read(FD, Buffer, sizeof(Buffer));
1195 if (close(FD) != 0 || Length < 0)
1196 return std::error_code(errno, std::generic_category());
1198 Result = identify_magic(StringRef(Buffer, Length));
1199 return std::error_code();
1202 std::error_code directory_entry::status(file_status &result) const {
1203 return fs::status(Path, result, FollowSymlinks);
1206 ErrorOr<perms> getPermissions(const Twine &Path) {
1208 if (std::error_code EC = status(Path, Status))
1211 return Status.permissions();
1214 } // end namespace fs
1215 } // end namespace sys
1216 } // end namespace llvm
1218 // Include the truly platform-specific parts.
1219 #if defined(LLVM_ON_UNIX)
1220 #include "Unix/Path.inc"
1222 #if defined(LLVM_ON_WIN32)
1223 #include "Windows/Path.inc"
1230 bool user_cache_directory(SmallVectorImpl<char> &Result, const Twine &Path1,
1231 const Twine &Path2, const Twine &Path3) {
1232 if (getUserCacheDir(Result)) {
1233 append(Result, Path1, Path2, Path3);
1239 } // end namespace path
1240 } // end namsspace sys
1241 } // end namespace llvm