24#include "llvm/Config/llvm-config.h"
50#include <system_error>
71 : Name(Name.str()), UID(UID), MTime(MTime), User(User), Group(Group),
72 Size(Size), Type(Type), Perms(Perms) {}
75 return Status(In.getName(), In.getUniqueID(), In.getLastModificationTime(),
76 In.getUser(), In.getGroup(), NewSize, In.getType(),
81 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
82 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
87 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
88 In.getUser(), In.getGroup(), In.getSize(), In.type(),
123 bool RequiresNullTerminator,
bool IsVolatile,
129 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
138 return WorkingDir.getError();
161 return StatusA.getError();
164 return StatusB.getError();
165 return StatusA->equivalent(*StatusB);
168#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
174 return Component ==
".." || Component ==
".";
194class RealFile :
public File {
195 friend class RealFileSystem;
199 std::string OriginalName;
202 std::optional<std::string> RealName;
204 RealFile(file_t RawFD, StringRef NewName, StringRef NewOriginalName)
205 : FD(RawFD), S(NewName, {}, {}, {}, {}, {},
207 OriginalName(NewOriginalName.str()) {
208 assert(FD.
isValid() &&
"Invalid or inactive file descriptor");
212 ~RealFile()
override;
214 ErrorOr<Status>
status()
override;
215 ErrorOr<std::string>
getName()
override;
216 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(
const Twine &Name,
218 bool RequiresNullTerminator,
219 bool IsVolatile)
override;
220 std::error_code close()
override;
221 void setPath(
const Twine &Path)
override;
226RealFile::~RealFile() { close(); }
228ErrorOr<Status> RealFile::status() {
231 assert(FD.isValid() &&
"cannot stat closed file");
232 if (!S.isStatusKnown()) {
233 file_status RealStatus;
241ErrorOr<std::string> RealFile::getName() {
244 SmallString<256>
Path;
252 return RealName->empty() ? S.getName().str() : *RealName;
255ErrorOr<std::unique_ptr<MemoryBuffer>>
256RealFile::getBuffer(
const Twine &Name, int64_t FileSize,
257 bool RequiresNullTerminator,
bool IsVolatile) {
260 assert(FD.isValid() &&
"cannot get buffer for closed file");
265std::error_code RealFile::close() {
273void RealFile::setPath(
const Twine &Path) {
276 RealName =
Path.str();
291class RealFileSystem :
public FileSystem {
293 explicit RealFileSystem(
bool LinkCWDToProcess) {
294 if (!LinkCWDToProcess) {
295 SmallString<128> PWD, RealPWD;
299 WD = WorkingDirectory{PWD, PWD};
301 WD = WorkingDirectory{PWD, RealPWD};
305 ErrorOr<Status>
status(
const Twine &Path)
override;
306 ErrorOr<std::unique_ptr<File>>
openFileForRead(
const Twine &Path)
override;
307 ErrorOr<std::unique_ptr<File>>
308 openFileForReadBinary(
const Twine &Path)
override;
309 directory_iterator dir_begin(
const Twine &Dir, std::error_code &EC)
override;
311 llvm::ErrorOr<std::string> getCurrentWorkingDirectory()
const override;
312 std::error_code setCurrentWorkingDirectory(
const Twine &Path)
override;
313 std::error_code isLocal(
const Twine &Path,
bool &Result)
override;
315 getDirectoryContentRealSources(
const Twine &Dir,
316 SmallVectorImpl<std::string> &Out)
override {
319 std::error_code getRealPath(
const Twine &Path,
320 SmallVectorImpl<char> &Output)
override;
324 unsigned IndentLevel)
const override;
329 Twine adjustPath(
const Twine &Path, SmallVectorImpl<char> &Storage)
const {
332 Path.toVector(Storage);
337 ErrorOr<std::unique_ptr<File>>
339 SmallString<256>
Path, Storage;
340 adjustPath(Name, Storage).toVector(Path);
344 return std::unique_ptr<File>(
new RealFile(*FDOrErr,
Name.str(), Path));
347 struct WorkingDirectory {
349 SmallString<128> Specified;
353 std::optional<llvm::ErrorOr<WorkingDirectory>> WD;
358ErrorOr<Status> RealFileSystem::status(
const Twine &Path) {
361 SmallString<256> Storage;
362 sys::fs::file_status RealStatus;
363 if (std::error_code EC =
369ErrorOr<std::unique_ptr<File>>
370RealFileSystem::openFileForRead(
const Twine &Name) {
376ErrorOr<std::unique_ptr<File>>
377RealFileSystem::openFileForReadBinary(
const Twine &Name) {
383llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory()
const {
387 return std::string(WD->get().Specified);
389 return WD->getError();
391 SmallString<128> Dir;
394 return std::string(Dir);
397std::error_code RealFileSystem::setCurrentWorkingDirectory(
const Twine &Path) {
404 adjustPath(Path, Storage).toVector(Absolute);
409 return std::make_error_code(std::errc::not_a_directory);
413 return std::error_code();
416std::error_code RealFileSystem::isLocal(
const Twine &Path,
bool &Result) {
419 SmallString<256> Storage;
423std::error_code RealFileSystem::getRealPath(
const Twine &Path,
424 SmallVectorImpl<char> &Output) {
427 SmallString<256> Storage;
431void RealFileSystem::printImpl(raw_ostream &OS, PrintType
Type,
432 unsigned IndentLevel)
const {
433 printIndent(OS, IndentLevel);
434 OS <<
"RealFileSystem using ";
453 return std::make_unique<RealFileSystem>(
false);
456std::optional<std::string>
465 if (S && S->isRegularFile())
466 return std::string(Path);
478 RealFSDirIter(
const Twine &Path, std::error_code &EC) {
486 std::error_code increment()
override {
501 std::error_code &EC) {
504 SmallString<128> Storage;
506 std::make_shared<RealFSDirIter>(adjustPath(Dir, Storage), EC));
514 FSList.push_back(std::move(BaseFS));
518 FSList.push_back(FS);
537 if ((*I)->exists(Path))
547 auto Result = (*I)->openFileForRead(Path);
557 return FSList.front()->getCurrentWorkingDirectory();
562 for (
auto &FS : FSList)
563 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
569 for (
auto &FS : FSList)
570 if (FS->exists(Path))
571 return FS->isLocal(Path, Result);
577 for (
const auto &FS : FSList)
578 if (FS->exists(Path))
579 return FS->getRealPath(Path, Output);
587 (*I)->getDirectoryContentRealSources(Dir, Out);
593 FS->visitChildFileSystems(Callback);
598 unsigned IndentLevel)
const {
599 printIndent(OS, IndentLevel);
600 OS <<
"OverlayFileSystem\n";
601 if (
Type == PrintType::Summary)
604 if (
Type == PrintType::Contents)
605 Type = PrintType::Summary;
607 FS->print(OS,
Type, IndentLevel + 1);
627 std::error_code incrementIter(
bool IsFirstTime) {
628 while (!IterList.
empty()) {
629 CurrentDirIter = IterList.
back();
640 std::error_code incrementDirIter(
bool IsFirstTime) {
641 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
642 "incrementing past end");
646 if (!EC && CurrentDirIter == directory_iterator())
647 EC = incrementIter(IsFirstTime);
651 std::error_code incrementImpl(
bool IsFirstTime) {
653 std::error_code
EC = incrementDirIter(IsFirstTime);
654 if (EC || CurrentDirIter == directory_iterator()) {
655 CurrentEntry = directory_entry();
658 CurrentEntry = *CurrentDirIter;
660 if (SeenNames.
insert(Name).second)
668 std::error_code &EC) {
669 for (
const auto &FS : FileSystems) {
671 directory_iterator Iter =
FS->dir_begin(Dir, FEC);
672 if (FEC && FEC != errc::no_such_file_or_directory) {
679 EC = incrementImpl(
true);
684 : IterList(DirIters) {
685 EC = incrementImpl(
true);
688 std::error_code increment()
override {
return incrementImpl(
false); }
694 std::error_code &EC) {
696 std::make_shared<CombiningDirIterImpl>(FSList, Dir.
str(), EC));
702void ProxyFileSystem::anchor() {}
720 std::string FileName;
724 : Kind(Kind), FileName(
std::string(
llvm::
sys::
path::filename(FileName))) {
736 virtual std::string
toString(
unsigned Indent)
const = 0;
741 std::unique_ptr<llvm::MemoryBuffer> Buffer;
753 std::string
toString(
unsigned Indent)
const override {
754 return (std::string(Indent,
' ') + Stat.getName() +
"\n").str();
764class InMemoryHardLink :
public InMemoryNode {
765 const InMemoryFile &ResolvedFile;
768 InMemoryHardLink(
StringRef Path,
const InMemoryFile &ResolvedFile)
769 : InMemoryNode(Path,
IME_HardLink), ResolvedFile(ResolvedFile) {}
770 const InMemoryFile &getResolvedFile()
const {
return ResolvedFile; }
772 Status getStatus(
const Twine &RequestedName)
const override {
773 return ResolvedFile.getStatus(RequestedName);
776 std::string
toString(
unsigned Indent)
const override {
777 return std::string(Indent,
' ') +
"HardLink to -> " +
778 ResolvedFile.toString(0);
781 static bool classof(
const InMemoryNode *
N) {
787 std::string TargetPath;
791 InMemorySymbolicLink(StringRef Path, StringRef TargetPath, Status Stat)
795 std::string
toString(
unsigned Indent)
const override {
796 return std::string(Indent,
' ') +
"SymbolicLink to -> " + TargetPath;
799 Status getStatus(
const Twine &RequestedName)
const override {
803 StringRef getTargetPath()
const {
return TargetPath; }
805 static bool classof(
const InMemoryNode *
N) {
813class InMemoryFileAdaptor :
public File {
814 const InMemoryFile &Node;
816 std::string RequestedName;
819 explicit InMemoryFileAdaptor(
const InMemoryFile &Node,
820 std::string RequestedName)
821 : Node(Node), RequestedName(std::
move(RequestedName)) {}
823 llvm::ErrorOr<Status>
status()
override {
824 return Node.getStatus(RequestedName);
827 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
828 getBuffer(
const Twine &Name, int64_t FileSize,
bool RequiresNullTerminator,
829 bool IsVolatile)
override {
830 llvm::MemoryBuffer *Buf = Node.getBuffer();
835 std::error_code close()
override {
return {}; }
837 void setPath(
const Twine &Path)
override { RequestedName =
Path.str(); }
843 std::map<std::string, std::unique_ptr<InMemoryNode>, std::less<>> Entries;
859 auto I = Entries.find(Name);
860 if (
I != Entries.end())
861 return I->second.get();
866 return Entries.emplace(Name, std::move(Child)).first->second.get();
874 std::string
toString(
unsigned Indent)
const override {
876 (std::string(Indent,
' ') + Stat.getName() +
"\n").str();
877 for (
const auto &Entry : Entries)
878 Result += Entry.second->toString(Indent + 2);
917 : Root(new
detail::InMemoryDirectory(
922 UseNormalizedPaths(UseNormalizedPaths) {}
927 return Root->toString(0);
930bool InMemoryFileSystem::addFile(
const Twine &
P, time_t ModificationTime,
931 std::unique_ptr<llvm::MemoryBuffer> Buffer,
932 std::optional<uint32_t>
User,
933 std::optional<uint32_t> Group,
934 std::optional<llvm::sys::fs::file_type>
Type,
935 std::optional<llvm::sys::fs::perms> Perms,
936 MakeNodeFn MakeNode) {
953 const auto ResolvedUser =
User.value_or(0);
954 const auto ResolvedGroup = Group.value_or(0);
971 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
976 Name, std::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
987 MakeNode({Dir->
getUniqueID(), Path, Name, ModificationTime,
988 std::move(Buffer), ResolvedUser, ResolvedGroup,
989 ResolvedType, ResolvedPerms}));
997 "Must be either file, hardlink or directory!");
1001 return Link->getResolvedFile().getBuffer()->getBuffer() ==
1002 Buffer->getBuffer();
1005 Buffer->getBuffer();
1008bool InMemoryFileSystem::addFile(
const Twine &
P, time_t ModificationTime,
1009 std::unique_ptr<llvm::MemoryBuffer> Buffer,
1010 std::optional<uint32_t>
User,
1011 std::optional<uint32_t> Group,
1012 std::optional<llvm::sys::fs::file_type>
Type,
1013 std::optional<llvm::sys::fs::perms> Perms) {
1014 return addFile(
P, ModificationTime, std::move(Buffer),
User, Group,
Type,
1017 -> std::unique_ptr<detail::InMemoryNode> {
1020 return std::make_unique<detail::InMemoryDirectory>(Stat);
1021 return std::make_unique<detail::InMemoryFile>(
1022 Stat, std::move(NNI.
Buffer));
1027 const Twine &
P, time_t ModificationTime,
1029 std::optional<uint32_t> Group, std::optional<llvm::sys::fs::file_type>
Type,
1030 std::optional<llvm::sys::fs::perms> Perms) {
1032 std::move(
User), std::move(Group), std::move(
Type),
1035 -> std::unique_ptr<detail::InMemoryNode> {
1038 return std::make_unique<detail::InMemoryDirectory>(Stat);
1039 return std::make_unique<detail::InMemoryFile>(
1040 Stat, std::move(NNI.
Buffer));
1045InMemoryFileSystem::lookupNode(
const Twine &
P,
bool FollowFinalSymlink,
1046 size_t SymlinkDepth)
const {
1072 if (
I == E && !FollowFinalSymlink)
1087 lookupNode(TargetPath,
true, SymlinkDepth + 1);
1115 return detail::NamedNodeOrError(Path, Dir);
1121 auto NewLinkNode = lookupNode(NewLink,
false);
1125 auto TargetNode = lookupNode(
Target,
true);
1130 return addFile(NewLink, 0,
nullptr, std::nullopt, std::nullopt, std::nullopt,
1132 return std::make_unique<detail::InMemoryHardLink>(
1140 std::optional<uint32_t>
User, std::optional<uint32_t> Group,
1141 std::optional<llvm::sys::fs::perms> Perms) {
1142 auto NewLinkNode = lookupNode(NewLink,
false);
1148 Target.toVector(TargetStr);
1150 return addFile(NewLinkStr, ModificationTime,
nullptr,
User, Group,
1153 return std::make_unique<detail::InMemorySymbolicLink>(
1159 auto Node = lookupNode(Path,
true);
1161 return (*Node)->getStatus(Path);
1162 return Node.getError();
1167 auto Node = lookupNode(Path,
true);
1169 return Node.getError();
1174 return std::unique_ptr<File>(
1175 new detail::InMemoryFileAdaptor(*
F, Path.str()));
1186 std::string RequestedDirName;
1188 void setCurrentEntry() {
1193 switch (I->second->getKind()) {
1202 if (
auto SymlinkTarget =
1203 FS->lookupNode(Path,
true)) {
1204 Path = SymlinkTarget.getName();
1205 Type = (*SymlinkTarget)->getStatus(Path).getType();
1222 std::string RequestedDirName)
1223 : FS(FS), I(Dir.begin()), E(Dir.end()),
1224 RequestedDirName(
std::
move(RequestedDirName)) {
1236 std::error_code &EC) {
1237 auto Node = lookupNode(Dir,
true);
1239 EC =
Node.getError();
1245 std::make_shared<DirIterator>(
this, *DirNode, Dir.
str()));
1264 WorkingDirectory = std::string(Path);
1271 if (!CWD || CWD->empty())
1273 Path.toVector(Output);
1286 unsigned IndentLevel)
const {
1287 printIndent(OS, IndentLevel);
1288 OS <<
"InMemoryFileSystem\n";
1303 const size_t n = Path.find_first_of(
"/\\");
1305 if (n !=
static_cast<size_t>(-1))
1325static bool isFileNotFound(std::error_code EC,
1337 assert(ExternalFS &&
"RedirectingFileSystem requires an external FS");
1338 if (
auto ExternalWorkingDirectory = ExternalFS->getCurrentWorkingDirectory())
1339 WorkingDirectory = *ExternalWorkingDirectory;
1349 std::error_code incrementImpl(
bool IsFirstTime) {
1350 assert((IsFirstTime || Current != End) &&
"cannot iterate past end");
1353 if (Current != End) {
1357 switch ((*Current)->getKind()) {
1378 : Dir(Path.str()), Current(Begin), End(End) {
1379 EC = incrementImpl(
true);
1383 return incrementImpl(
false);
1397 RedirectingFSDirRemapIterImpl(std::string DirPath,
1399 : Dir(
std::
move(DirPath)), DirStyle(getExistingStyle(Dir)),
1400 ExternalIter(ExtIter) {
1405 void setCurrentEntry() {
1416 std::error_code increment()
override {
1419 if (!EC && ExternalIter != llvm::vfs::directory_iterator())
1422 CurrentEntry = directory_entry();
1428llvm::ErrorOr<std::string>
1430 return WorkingDirectory;
1440 Path.toVector(AbsolutePath);
1441 if (std::error_code EC = makeAbsolute(AbsolutePath))
1443 WorkingDirectory = std::string(AbsolutePath);
1452 if (makeAbsolute(Path))
1455 return ExternalFS->isLocal(Path, Result);
1470 return WorkingDir.getError();
1472 return makeAbsolute(WorkingDir.get(), Path);
1476RedirectingFileSystem::makeAbsolute(
StringRef WorkingDir,
1482 if (!WorkingDir.
empty() &&
1486 return std::error_code();
1498 std::string
Result = std::string(WorkingDir);
1499 StringRef Dir(Result);
1515 std::error_code &EC) {
1519 EC = makeAbsolute(Path);
1526 isFileNotFound(Result.getError()))
1527 return ExternalFS->dir_begin(Path, EC);
1529 EC = Result.getError();
1537 isFileNotFound(S.
getError(), Result->E))
1538 return ExternalFS->dir_begin(Dir, EC);
1544 if (!S->isDirectory()) {
1552 std::error_code RedirectEC;
1553 if (
auto ExtRedirect = Result->getExternalRedirect()) {
1555 RedirectIter = ExternalFS->dir_begin(*ExtRedirect, RedirectEC);
1557 if (!RE->useExternalName(UseExternalNames)) {
1561 std::string(Path), RedirectIter));
1567 Path, DE->contents_begin(), DE->contents_end(), RedirectEC));
1580 return RedirectIter;
1583 std::error_code ExternalEC;
1594 switch (Redirection) {
1608 std::make_shared<CombiningDirIterImpl>(Iters, EC)};
1615 OverlayFileDir = Dir.
str();
1619 return OverlayFileDir;
1636 std::vector<StringRef> R;
1637 R.reserve(Roots.size());
1638 for (
const auto &Root : Roots)
1639 R.push_back(Root->getName());
1644 unsigned IndentLevel)
const {
1646 OS <<
"RedirectingFileSystem (UseExternalNames: "
1647 << (UseExternalNames ?
"true" :
"false") <<
")\n";
1651 for (
const auto &Root : Roots)
1655 OS <<
"ExternalFS:\n";
1662 unsigned IndentLevel)
const {
1664 OS <<
"'" << E->getName() <<
"'";
1666 switch (E->getKind()) {
1671 for (std::unique_ptr<Entry> &SubEntry :
1673 printEntry(OS, SubEntry.get(), IndentLevel + 1);
1679 OS <<
" -> '" << RE->getExternalContentsPath() <<
"'";
1680 switch (RE->getUseName()) {
1684 OS <<
" (UseExternalName: true)";
1687 OS <<
" (UseExternalName: false)";
1698 Callback(*ExternalFS);
1699 ExternalFS->visitChildFileSystems(Callback);
1715 error(
N,
"expected string");
1718 Result = S->getValue(Storage);
1723 bool parseScalarBool(
yaml::Node *
N,
bool &Result) {
1726 if (!parseScalarString(
N,
Value, Storage))
1729 if (
Value.equals_insensitive(
"true") ||
Value.equals_insensitive(
"on") ||
1730 Value.equals_insensitive(
"yes") ||
Value ==
"1") {
1733 }
else if (
Value.equals_insensitive(
"false") ||
1734 Value.equals_insensitive(
"off") ||
1735 Value.equals_insensitive(
"no") ||
Value ==
"0") {
1740 error(
N,
"expected boolean value");
1744 std::optional<RedirectingFileSystem::RedirectKind>
1748 if (!parseScalarString(
N,
Value, Storage))
1749 return std::nullopt;
1751 if (
Value.equals_insensitive(
"fallthrough")) {
1753 }
else if (
Value.equals_insensitive(
"fallback")) {
1755 }
else if (
Value.equals_insensitive(
"redirect-only")) {
1758 return std::nullopt;
1761 std::optional<RedirectingFileSystem::RootRelativeKind>
1765 if (!parseScalarString(
N,
Value, Storage))
1766 return std::nullopt;
1767 if (
Value.equals_insensitive(
"cwd")) {
1769 }
else if (
Value.equals_insensitive(
"overlay-dir")) {
1772 return std::nullopt;
1779 KeyStatus(
bool Required =
false) : Required(Required) {}
1782 using KeyStatusPair = std::pair<StringRef, KeyStatus>;
1788 if (It == Keys.
end()) {
1789 error(KeyNode,
"unknown key");
1792 KeyStatus &S = It->second;
1803 for (
const auto &
I : Keys) {
1804 if (
I.second.Required && !
I.second.Seen) {
1805 error(Obj,
Twine(
"missing key '") +
I.first +
"'");
1817 for (
const auto &Root : FS->Roots) {
1818 if (Name == Root->getName()) {
1819 ParentEntry = Root.get();
1825 for (std::unique_ptr<RedirectingFileSystem::Entry> &Content :
1829 if (DirContent && Name == Content->getName())
1835 std::unique_ptr<RedirectingFileSystem::Entry> E =
1836 std::make_unique<RedirectingFileSystem::DirectoryEntry>(
1838 std::chrono::system_clock::now(), 0, 0, 0,
1842 FS->Roots.push_back(std::move(E));
1843 ParentEntry = FS->Roots.back().get();
1848 DE->addContent(std::move(E));
1849 return DE->getLastContent();
1864 NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1865 for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
1867 uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1871 assert(NewParentE &&
"Parent entry must exist");
1875 std::make_unique<RedirectingFileSystem::DirectoryRemapEntry>(
1876 Name, DR->getExternalContentsPath(), DR->getUseName()));
1880 assert(NewParentE &&
"Parent entry must exist");
1883 DE->addContent(std::make_unique<RedirectingFileSystem::FileEntry>(
1884 Name, FE->getExternalContentsPath(), FE->getUseName()));
1890 std::unique_ptr<RedirectingFileSystem::Entry>
1891 parseEntry(yaml::Node *
N, RedirectingFileSystem *FS,
bool IsRootEntry) {
1894 error(
N,
"expected mapping node for file or directory entry");
1898 KeyStatusPair Fields[] = {
1899 KeyStatusPair(
"name",
true),
1900 KeyStatusPair(
"type",
true),
1901 KeyStatusPair(
"contents",
false),
1902 KeyStatusPair(
"external-contents",
false),
1903 KeyStatusPair(
"use-external-name",
false),
1906 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
1908 enum { CF_NotSet, CF_List, CF_External } ContentsField = CF_NotSet;
1909 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>>
1911 SmallString<256> ExternalContentsPath;
1912 SmallString<256>
Name;
1913 yaml::Node *NameValueNode =
nullptr;
1917 for (
auto &
I : *M) {
1921 SmallString<256> Buffer;
1922 if (!parseScalarString(
I.getKey(),
Key, Buffer))
1925 if (!checkDuplicateOrUnknownKey(
I.getKey(),
Key, Keys))
1929 if (
Key ==
"name") {
1930 if (!parseScalarString(
I.getValue(),
Value, Buffer))
1933 NameValueNode =
I.getValue();
1937 }
else if (
Key ==
"type") {
1938 if (!parseScalarString(
I.getValue(),
Value, Buffer))
1940 if (
Value ==
"file")
1942 else if (
Value ==
"directory")
1944 else if (
Value ==
"directory-remap")
1947 error(
I.getValue(),
"unknown value for 'type'");
1950 }
else if (
Key ==
"contents") {
1951 if (ContentsField != CF_NotSet) {
1953 "entry already has 'contents' or 'external-contents'");
1956 ContentsField = CF_List;
1960 error(
I.getValue(),
"expected array");
1964 for (
auto &
I : *Contents) {
1965 if (std::unique_ptr<RedirectingFileSystem::Entry>
E =
1966 parseEntry(&
I, FS,
false))
1967 EntryArrayContents.push_back(std::move(
E));
1971 }
else if (
Key ==
"external-contents") {
1972 if (ContentsField != CF_NotSet) {
1974 "entry already has 'contents' or 'external-contents'");
1977 ContentsField = CF_External;
1978 if (!parseScalarString(
I.getValue(),
Value, Buffer))
1981 SmallString<256> FullPath;
1982 if (
FS->IsRelativeOverlay) {
1983 FullPath =
FS->getOverlayFileDir();
1985 "External contents prefix directory must exist");
1986 SmallString<256> AbsFullPath =
Value;
1987 if (
FS->makeAbsolute(FullPath, AbsFullPath)) {
1988 error(
N,
"failed to make 'external-contents' absolute");
1991 FullPath = AbsFullPath;
1998 FullPath = canonicalize(FullPath);
1999 ExternalContentsPath = FullPath.
str();
2000 }
else if (
Key ==
"use-external-name") {
2002 if (!parseScalarBool(
I.getValue(), Val))
2015 if (ContentsField == CF_NotSet) {
2016 error(
N,
"missing key 'contents' or 'external-contents'");
2019 if (!checkMissingKeys(
N, Keys))
2025 error(
N,
"'use-external-name' is not supported for 'directory' entries");
2030 ContentsField == CF_List) {
2031 error(
N,
"'contents' is not supported for 'directory-remap' entries");
2040 path_style = sys::path::Style::posix;
2042 sys::path::Style::windows_backslash)) {
2043 path_style = sys::path::Style::windows_backslash;
2049 if (
FS->RootRelative ==
2050 RedirectingFileSystem::RootRelativeKind::OverlayDir) {
2051 StringRef FullPath =
FS->getOverlayFileDir();
2052 assert(!FullPath.
empty() &&
"Overlay file directory must exist");
2053 EC =
FS->makeAbsolute(FullPath, Name);
2054 Name = canonicalize(Name);
2056 EC =
FS->makeAbsolute(Name);
2059 assert(NameValueNode &&
"Name presence should be checked earlier");
2062 "entry with relative path at the root level is not discoverable");
2066 ? sys::path::Style::posix
2067 : sys::path::Style::windows_backslash;
2072 if (path_style == sys::path::Style::windows_backslash &&
2073 getExistingStyle(Name) != sys::path::Style::windows_backslash)
2074 path_style = sys::path::Style::windows_slash;
2078 StringRef Trimmed =
Name;
2080 while (Trimmed.
size() > RootPathLen &&
2082 Trimmed = Trimmed.
slice(0, Trimmed.
size() - 1);
2087 std::unique_ptr<RedirectingFileSystem::Entry>
Result;
2090 Result = std::make_unique<RedirectingFileSystem::FileEntry>(
2091 LastComponent, std::move(ExternalContentsPath), UseExternalName);
2094 Result = std::make_unique<RedirectingFileSystem::DirectoryRemapEntry>(
2095 LastComponent, std::move(ExternalContentsPath), UseExternalName);
2098 Result = std::make_unique<RedirectingFileSystem::DirectoryEntry>(
2099 LastComponent, std::move(EntryArrayContents),
2113 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> Entries;
2114 Entries.push_back(std::move(Result));
2115 Result = std::make_unique<RedirectingFileSystem::DirectoryEntry>(
2116 *
I, std::move(Entries),
2130 error(Root,
"expected mapping node");
2134 KeyStatusPair Fields[] = {
2135 KeyStatusPair(
"version",
true),
2136 KeyStatusPair(
"case-sensitive",
false),
2137 KeyStatusPair(
"use-external-names",
false),
2138 KeyStatusPair(
"root-relative",
false),
2139 KeyStatusPair(
"overlay-relative",
false),
2140 KeyStatusPair(
"fallthrough",
false),
2141 KeyStatusPair(
"redirecting-with",
false),
2142 KeyStatusPair(
"roots",
true),
2146 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> RootEntries;
2149 for (
auto &
I : *Top) {
2152 if (!parseScalarString(
I.getKey(),
Key, KeyBuffer))
2155 if (!checkDuplicateOrUnknownKey(
I.getKey(),
Key, Keys))
2158 if (
Key ==
"roots") {
2161 error(
I.getValue(),
"expected array");
2165 for (
auto &
I : *Roots) {
2166 if (std::unique_ptr<RedirectingFileSystem::Entry> E =
2167 parseEntry(&
I, FS,
true))
2168 RootEntries.push_back(std::move(E));
2172 }
else if (
Key ==
"version") {
2175 if (!parseScalarString(
I.getValue(), VersionString, Storage))
2179 error(
I.getValue(),
"expected integer");
2183 error(
I.getValue(),
"invalid version number");
2187 error(
I.getValue(),
"version mismatch, expected 0");
2190 }
else if (
Key ==
"case-sensitive") {
2191 if (!parseScalarBool(
I.getValue(), FS->CaseSensitive))
2193 }
else if (
Key ==
"overlay-relative") {
2194 if (!parseScalarBool(
I.getValue(), FS->IsRelativeOverlay))
2196 }
else if (
Key ==
"use-external-names") {
2197 if (!parseScalarBool(
I.getValue(), FS->UseExternalNames))
2199 }
else if (
Key ==
"fallthrough") {
2200 if (Keys[
"redirecting-with"].Seen) {
2202 "'fallthrough' and 'redirecting-with' are mutually exclusive");
2206 bool ShouldFallthrough =
false;
2207 if (!parseScalarBool(
I.getValue(), ShouldFallthrough))
2210 if (ShouldFallthrough) {
2215 }
else if (
Key ==
"redirecting-with") {
2216 if (Keys[
"fallthrough"].Seen) {
2218 "'fallthrough' and 'redirecting-with' are mutually exclusive");
2222 if (
auto Kind = parseRedirectKind(
I.getValue())) {
2223 FS->Redirection = *Kind;
2225 error(
I.getValue(),
"expected valid redirect kind");
2228 }
else if (
Key ==
"root-relative") {
2229 if (
auto Kind = parseRootRelativeKind(
I.getValue())) {
2230 FS->RootRelative = *Kind;
2232 error(
I.getValue(),
"expected valid root-relative kind");
2240 if (Stream.failed())
2243 if (!checkMissingKeys(Top, Keys))
2249 for (
auto &E : RootEntries)
2250 uniqueOverlayTree(FS, E.get());
2256std::unique_ptr<RedirectingFileSystem>
2259 StringRef YAMLFilePath,
void *DiagContext,
2267 if (DI == Stream.
end() || !Root) {
2274 std::unique_ptr<RedirectingFileSystem> FS(
2275 new RedirectingFileSystem(ExternalFS));
2277 if (!YAMLFilePath.
empty()) {
2287 std::error_code EC = FS->makeAbsolute(OverlayAbsDir);
2288 assert(!EC &&
"Overlay dir final path must be absolute");
2290 FS->setOverlayFileDir(OverlayAbsDir);
2293 if (!
P.parse(Root, FS.get()))
2300 ArrayRef<std::pair<std::string, std::string>> RemappedFiles,
2302 std::unique_ptr<RedirectingFileSystem> FS(
2303 new RedirectingFileSystem(ExternalFS));
2304 FS->UseExternalNames = UseExternalNames;
2312 auto EC = ExternalFS->makeAbsolute(From);
2314 assert(!EC &&
"Could not make absolute path");
2332 assert(Parent &&
"File without a directory?");
2334 auto EC = ExternalFS->makeAbsolute(To);
2336 assert(!EC &&
"Could not make absolute path");
2340 auto NewFile = std::make_unique<RedirectingFileSystem::FileEntry>(
2344 ToEntry = NewFile.get();
2346 std::move(NewFile));
2362 getExistingStyle(DRE->getExternalContentsPath()));
2363 ExternalRedirect = std::string(Redirect);
2375std::error_code RedirectingFileSystem::makeCanonicalForLookup(
2377 if (std::error_code EC = makeAbsolute(Path))
2381 canonicalize(
StringRef(Path.data(), Path.size()));
2382 if (CanonicalPath.
empty())
2385 Path.assign(CanonicalPath.
begin(), CanonicalPath.
end());
2392 if (std::error_code EC = makeCanonicalForLookup(CanonicalPath))
2402 for (
const auto &Root : Roots) {
2404 lookupPathImpl(Start,
End, Root.get(), Entries);
2408 Result->Parents = std::move(Entries);
2419RedirectingFileSystem::lookupPathImpl(
2425 "Paths should not contain traversal components");
2430 if (!FromName.
empty()) {
2431 if (!pathComponentMatches(*Start, FromName))
2438 return LookupResult(From, Start,
End);
2446 return LookupResult(From, Start,
End);
2449 for (
const std::unique_ptr<RedirectingFileSystem::Entry> &DirEntry :
2453 lookupPathImpl(Start,
End, DirEntry.get(), Entries);
2463 bool UseExternalNames,
2468 return ExternalStatus;
2470 Status S = ExternalStatus;
2471 if (!UseExternalNames)
2478ErrorOr<Status> RedirectingFileSystem::status(
2479 const Twine &LookupPath,
const Twine &OriginalPath,
2480 const RedirectingFileSystem::LookupResult &Result) {
2481 if (std::optional<StringRef> ExtRedirect =
Result.getExternalRedirect()) {
2482 SmallString<256> RemappedPath((*ExtRedirect).str());
2483 if (std::error_code EC = makeAbsolute(RemappedPath))
2486 ErrorOr<Status> S = ExternalFS->status(RemappedPath);
2492 RE->useExternalName(UseExternalNames), *S);
2500RedirectingFileSystem::getExternalStatus(
const Twine &LookupPath,
2501 const Twine &OriginalPath)
const {
2502 auto Result = ExternalFS->status(LookupPath);
2506 if (!Result ||
Result->ExposesExternalVFSPath)
2515 if (std::error_code EC = makeAbsolute(Path))
2531 isFileNotFound(Result.getError()))
2532 return getExternalStatus(Path, OriginalPath);
2533 return Result.getError();
2538 isFileNotFound(S.
getError(), Result->E)) {
2542 return getExternalStatus(Path, OriginalPath);
2552 if (makeAbsolute(Path))
2558 if (ExternalFS->exists(Path))
2567 isFileNotFound(Result.getError()))
2568 return ExternalFS->exists(Path);
2572 std::optional<StringRef> ExtRedirect = Result->getExternalRedirect();
2579 if (makeAbsolute(RemappedPath))
2582 if (ExternalFS->exists(RemappedPath))
2589 return ExternalFS->exists(Path);
2598class FileWithFixedStatus :
public File {
2599 std::unique_ptr<File> InnerFile;
2603 FileWithFixedStatus(std::unique_ptr<File> InnerFile,
Status S)
2609 getBuffer(
const Twine &Name, int64_t FileSize,
bool RequiresNullTerminator,
2610 bool IsVolatile)
override {
2611 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
2615 std::error_code close()
override {
return InnerFile->close(); }
2617 void setPath(
const Twine &Path)
override { S = S.
copyWithNewName(S, Path); }
2622ErrorOr<std::unique_ptr<File>>
2626 if (!Result || (*Result)->status()->ExposesExternalVFSPath)
2630 auto Name =
F->get()->getName();
2631 if (Name && Name.get() !=
P.str())
2632 F->get()->setPath(
P);
2641 if (std::error_code EC = makeAbsolute(Path))
2657 isFileNotFound(Result.getError()))
2659 return Result.getError();
2662 if (!Result->getExternalRedirect())
2665 StringRef ExtRedirect = *Result->getExternalRedirect();
2667 if (std::error_code EC = makeAbsolute(RemappedPath))
2674 if (!ExternalFile) {
2676 isFileNotFound(ExternalFile.getError(), Result->E)) {
2682 return ExternalFile;
2685 auto ExternalStatus = (*ExternalFile)->status();
2686 if (!ExternalStatus)
2687 return ExternalStatus.getError();
2692 OriginalPath, RE->useExternalName(UseExternalNames), *ExternalStatus);
2693 return std::unique_ptr<File>(
2694 std::make_unique<FileWithFixedStatus>(std::move(*ExternalFile), S));
2703 if (std::error_code EC = makeAbsolute(Path))
2709 std::error_code EC = ExternalFS->getRealPath(Path, Output);
2719 isFileNotFound(Result.getError()))
2720 return ExternalFS->getRealPath(Path, Output);
2721 return Result.getError();
2726 if (
auto ExtRedirect = Result->getExternalRedirect()) {
2727 auto P = ExternalFS->getRealPath(*ExtRedirect, Output);
2729 isFileNotFound(
P, Result->E)) {
2733 return ExternalFS->getRealPath(Path, Output);
2741 Result->getPath(Output);
2752 if (makeAbsolute(Path))
2761 if (ConsultsExternalFS)
2762 ExternalFS->getDirectoryContentRealSources(Path, Out);
2766 switch (Result->E->getKind()) {
2776 if (!makeAbsolute(RemappedPath))
2777 ExternalFS->getDirectoryContentRealSources(RemappedPath, Out);
2783 if (ConsultsExternalFS)
2784 ExternalFS->getDirectoryContentRealSources(Path, Out);
2787std::unique_ptr<FileSystem>
2790 StringRef YAMLFilePath,
void *DiagContext,
2793 YAMLFilePath, DiagContext,
2794 std::move(ExternalFS));
2803 assert(DE &&
"Must be a directory");
2804 for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
2806 Path.push_back(SubEntry->getName());
2815 assert(DR &&
"Must be a directory remap");
2817 for (
auto &Comp : Path)
2826 assert(FE &&
"Must be a file");
2828 for (
auto &Comp : Path)
2844 static std::atomic<unsigned> UID;
2845 unsigned ID = ++UID;
2848 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
2856 Mappings.emplace_back(VirtualPath, RealPath, IsDirectory);
2860 addEntry(VirtualPath, RealPath,
false);
2865 addEntry(VirtualPath, RealPath,
true);
2874 unsigned getDirIndent() {
return 4 * DirStack.
size(); }
2875 unsigned getFileIndent() {
return 4 * (DirStack.
size() + 1); }
2879 void endDirectory();
2886 std::optional<bool> UseExternalNames,
2887 std::optional<bool> IsCaseSensitive,
2888 std::optional<bool> IsOverlayRelative, StringRef OverlayDir);
2893bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
2894 using namespace llvm::sys;
2899 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
2900 if (*IParent != *IChild)
2904 return IParent == EParent;
2907StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
2909 assert(containedIn(Parent, Path));
2910 return Path.substr(Parent.
size() + 1);
2913void JSONWriter::startDirectory(StringRef Path) {
2915 DirStack.
empty() ?
Path : containedPart(DirStack.
back(), Path);
2917 unsigned Indent = getDirIndent();
2918 OS.
indent(Indent) <<
"{\n";
2919 OS.
indent(Indent + 2) <<
"'type': 'directory',\n";
2921 OS.
indent(Indent + 2) <<
"'contents': [\n";
2924void JSONWriter::endDirectory() {
2925 unsigned Indent = getDirIndent();
2926 OS.
indent(Indent + 2) <<
"]\n";
2927 OS.
indent(Indent) <<
"}";
2932void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
2933 unsigned Indent = getFileIndent();
2934 OS.
indent(Indent) <<
"{\n";
2935 OS.
indent(Indent + 2) <<
"'type': 'file',\n";
2937 OS.
indent(Indent + 2) <<
"'external-contents': \""
2939 OS.
indent(Indent) <<
"}";
2943 std::optional<bool> UseExternalNames,
2944 std::optional<bool> IsCaseSensitive,
2945 std::optional<bool> IsOverlayRelative,
2947 using namespace llvm::sys;
2951 if (IsCaseSensitive)
2952 OS <<
" 'case-sensitive': '" << (*IsCaseSensitive ?
"true" :
"false")
2954 if (UseExternalNames)
2955 OS <<
" 'use-external-names': '" << (*UseExternalNames ?
"true" :
"false")
2957 bool UseOverlayRelative =
false;
2958 if (IsOverlayRelative) {
2959 UseOverlayRelative = *IsOverlayRelative;
2960 OS <<
" 'overlay-relative': '" << (UseOverlayRelative ?
"true" :
"false")
2963 OS <<
" 'roots': [\n";
2965 if (!Entries.
empty()) {
2973 if (UseOverlayRelative) {
2975 "Overlay dir must be contained in RPath");
2979 bool IsCurrentDirEmpty =
true;
2980 if (!
Entry.IsDirectory) {
2982 IsCurrentDirEmpty =
false;
2988 if (Dir == DirStack.
back()) {
2989 if (!IsCurrentDirEmpty) {
2993 bool IsDirPoppedFromStack =
false;
2994 while (!DirStack.
empty() && !containedIn(DirStack.
back(), Dir)) {
2997 IsDirPoppedFromStack =
true;
2999 if (IsDirPoppedFromStack || !IsCurrentDirEmpty) {
3002 startDirectory(Dir);
3003 IsCurrentDirEmpty =
true;
3006 if (UseOverlayRelative) {
3008 "Overlay dir must be contained in RPath");
3011 if (!
Entry.IsDirectory) {
3013 IsCurrentDirEmpty =
false;
3017 while (!DirStack.
empty()) {
3030 return LHS.VPath < RHS.VPath;
3033 JSONWriter(OS).
write(Mappings, UseExternalNames, IsCaseSensitive,
3034 IsOverlayRelative, OverlayDir);
3042 State = std::make_shared<detail::RecDirIterState>();
3043 State->Stack.push_back(
I);
3049 assert(FS && State && !State->Stack.empty() &&
"incrementing past end");
3050 assert(!State->Stack.back()->path().empty() &&
"non-canonical end iterator");
3053 if (State->HasNoPushRequest)
3054 State->HasNoPushRequest =
false;
3058 FS->dir_begin(State->Stack.back()->path(), EC);
3060 State->Stack.push_back(
I);
3066 while (!State->Stack.empty() && State->Stack.back().increment(EC) ==
End)
3067 State->Stack.pop_back();
3069 if (State->Stack.empty())
3081unsigned ::llvm::IntrusiveRefCntPtrInfo<FileSystem>::useCount(
3083 return FS->UseCount();
3086void ::llvm::IntrusiveRefCntPtrInfo<FileSystem>::retain(
FileSystem *FS) {
3090void ::llvm::IntrusiveRefCntPtrInfo<FileSystem>::release(
FileSystem *FS) {
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseMap class.
Provides ErrorOr<T> smart pointer.
static void makeAbsolute(vfs::FileSystem &VFS, SmallVectorImpl< char > &Path)
Make Path absolute.
This file defines the RefCountedBase, ThreadSafeRefCountedBase, and IntrusiveRefCntPtr classes.
static void printImpl(const MCAsmInfo &MAI, raw_ostream &OS, const MCSpecifierExpr &Expr)
static StringRef getName(Value *V)
This file defines the SmallString class.
This file defines the SmallVector class.
StringSet - A set-like wrapper for the StringMap.
static void DiagHandler(const SMDiagnostic &Diag, void *Context)
static void getVFSEntries(RedirectingFileSystem::Entry *SrcE, SmallVectorImpl< StringRef > &Path, SmallVectorImpl< YAMLVFSEntry > &Entries)
static Status getRedirectedFileStatus(const Twine &OriginalPath, bool UseExternalNames, Status ExternalStatus)
static bool pathHasTraversal(StringRef Path)
static bool isTraversalComponent(StringRef Component)
Defines the virtual file system interface vfs::FileSystem.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & front() const
Get the first element.
bool empty() const
Check if the array is empty.
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
iterator find(const_arg_type_t< KeyT > Val)
Represents either an error or a value T.
std::error_code getError() const
Error takeError()
Take ownership of the stored error.
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
This interface provides simple read-only access to a block of memory, and provides simple methods for...
static ErrorOr< std::unique_ptr< MemoryBuffer > > getOpenFile(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Given an already-open file descriptor, read the file and return a MemoryBuffer.
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
StringRef getBuffer() const
Represents a location in source code.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
LLVM_ABI void PrintMessage(raw_ostream &OS, SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges={}, ArrayRef< SMFixIt > FixIts={}, bool ShowColors=true) const
Emit a message about the specified location with the specified string.
void(*)(const SMDiagnostic &, void *Context) DiagHandlerTy
Clients that want to handle their own diagnostics in a custom way can register a function pointer+con...
void setDiagHandler(DiagHandlerTy DH, void *Ctx=nullptr)
Specify a diagnostic handler to be invoked every time PrintMessage is called.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Represent a constant reference to a string, i.e.
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
std::string str() const
Get the contents as an std::string.
constexpr bool empty() const
Check if the string is empty.
char back() const
Get the last character in the string.
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
constexpr size_t size() const
Get the string size.
StringSet - A wrapper for StringMap that provides set-like functionality.
std::pair< typename Base::iterator, bool > insert(StringRef key)
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
LLVM_ABI void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM Value Representation.
An opaque object representing a hash code.
This class implements an extremely fast bulk output stream that can only output to a stream.
raw_ostream & write(unsigned char C)
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
const std::string & path() const
directory_iterator - Iterates through the entries in path.
directory_iterator & increment(std::error_code &ec)
Represents the result of a call to sys::fs::status().
The virtual file system interface.
llvm::function_ref< void(FileSystem &)> VisitCallbackTy
virtual llvm::ErrorOr< std::string > getCurrentWorkingDirectory() const =0
Get the working directory of this file system.
virtual bool exists(const Twine &Path)
Check whether Path exists.
virtual llvm::ErrorOr< std::unique_ptr< File > > openFileForReadBinary(const Twine &Path)
Get a File object for the binary file at Path, if one exists.
virtual std::error_code makeAbsolute(SmallVectorImpl< char > &Path) const
Make Path an absolute path.
virtual llvm::ErrorOr< std::unique_ptr< File > > openFileForRead(const Twine &Path)=0
Get a File object for the text file at Path, if one exists.
virtual std::error_code getRealPath(const Twine &Path, SmallVectorImpl< char > &Output)
Gets real path of Path e.g.
void printIndent(raw_ostream &OS, unsigned IndentLevel) const
LLVM_DUMP_METHOD void dump() const
void print(raw_ostream &OS, PrintType Type=PrintType::Contents, unsigned IndentLevel=0) const
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const Twine &Name, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false, bool IsText=true)
This is a convenience method that opens a file, gets its content and then closes the file.
llvm::ErrorOr< bool > equivalent(const Twine &A, const Twine &B)
virtual std::error_code isLocal(const Twine &Path, bool &Result)
Is the file mounted on a local filesystem?
virtual llvm::ErrorOr< Status > status(const Twine &Path)=0
Get the status of the entry at Path, if one exists.
static ErrorOr< std::unique_ptr< File > > getWithPath(ErrorOr< std::unique_ptr< File > > Result, const Twine &P)
virtual ~File()
Destroy the file after closing it (if open).
Adaptor from InMemoryDir::iterator to directory_iterator.
DirIterator(const InMemoryFileSystem *FS, const detail::InMemoryDirectory &Dir, std::string RequestedDirName)
std::error_code increment() override
Sets CurrentEntry to the next entry in the directory on success, to directory_entry() at end,...
std::error_code isLocal(const Twine &Path, bool &Result) override
directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override
std::error_code getRealPath(const Twine &Path, SmallVectorImpl< char > &Output) override
Canonicalizes Path by combining with the current working directory and normalizing the path (e....
~InMemoryFileSystem() override
static constexpr size_t MaxSymlinkDepth
Arbitrary max depth to search through symlinks.
InMemoryFileSystem(bool UseNormalizedPaths=true)
bool useNormalizedPaths() const
Return true if this file system normalizes . and .. in paths.
void printImpl(raw_ostream &OS, PrintType Type, unsigned IndentLevel) const override
llvm::ErrorOr< std::string > getCurrentWorkingDirectory() const override
bool addHardLink(const Twine &NewLink, const Twine &Target)
Add a hard link to a file.
std::string toString() const
bool addFileNoOwn(const Twine &Path, time_t ModificationTime, const llvm::MemoryBufferRef &Buffer, std::optional< uint32_t > User=std::nullopt, std::optional< uint32_t > Group=std::nullopt, std::optional< llvm::sys::fs::file_type > Type=std::nullopt, std::optional< llvm::sys::fs::perms > Perms=std::nullopt)
Add a buffer to the VFS with a path.
bool addSymbolicLink(const Twine &NewLink, const Twine &Target, time_t ModificationTime, std::optional< uint32_t > User=std::nullopt, std::optional< uint32_t > Group=std::nullopt, std::optional< llvm::sys::fs::perms > Perms=std::nullopt)
Add a symbolic link.
std::error_code setCurrentWorkingDirectory(const Twine &Path) override
llvm::ErrorOr< Status > status(const Twine &Path) override
llvm::ErrorOr< std::unique_ptr< File > > openFileForRead(const Twine &Path) override
directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override
void visitChildFileSystems(VisitCallbackTy Callback) override
llvm::ErrorOr< std::unique_ptr< File > > openFileForRead(const Twine &Path) override
std::error_code getRealPath(const Twine &Path, SmallVectorImpl< char > &Output) override
std::error_code setCurrentWorkingDirectory(const Twine &Path) override
void pushOverlay(IntrusiveRefCntPtr< FileSystem > FS)
Pushes a file system on top of the stack.
OverlayFileSystem(IntrusiveRefCntPtr< FileSystem > Base)
llvm::ErrorOr< std::string > getCurrentWorkingDirectory() const override
void getDirectoryContentRealSources(const Twine &Dir, SmallVectorImpl< std::string > &Out) override
iterator overlays_end()
Get an iterator pointing one-past the least recently added file system.
std::error_code isLocal(const Twine &Path, bool &Result) override
bool exists(const Twine &Path) override
llvm::ErrorOr< Status > status(const Twine &Path) override
iterator overlays_begin()
Get an iterator pointing to the most recently added file system.
FileSystemList::reverse_iterator iterator
void printImpl(raw_ostream &OS, PrintType Type, unsigned IndentLevel) const override
Directory iterator implementation for RedirectingFileSystem's directory entries.
std::error_code increment() override
Sets CurrentEntry to the next entry in the directory on success, to directory_entry() at end,...
RedirectingFSDirIterImpl(const Twine &Path, RedirectingFileSystem::DirectoryEntry::iterator Begin, RedirectingFileSystem::DirectoryEntry::iterator End, std::error_code &EC)
A helper class to hold the common YAML parsing state.
RedirectingFileSystemParser(yaml::Stream &S)
static RedirectingFileSystem::Entry * lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name, RedirectingFileSystem::Entry *ParentEntry=nullptr)
bool parse(yaml::Node *Root, RedirectingFileSystem *FS)
decltype(Contents)::iterator iterator
A single file or directory in the VFS.
StringRef getName() const
EntryKind getKind() const
A virtual file system parsed from a YAML file.
@ OverlayDir
The roots are relative to the directory where the Overlay YAML file.
@ CWD
The roots are relative to the current working directory.
bool exists(const Twine &Path) override
Check whether Path exists.
void printImpl(raw_ostream &OS, PrintType Type, unsigned IndentLevel) const override
friend class RedirectingFileSystemParser
std::vector< llvm::StringRef > getRoots() const
directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override
Get a directory_iterator for Dir.
ErrorOr< LookupResult > lookupPath(StringRef Path) const
Looks up Path in Roots and returns a LookupResult giving the matched entry and, if the entry was a Fi...
RedirectKind
The type of redirection to perform.
@ Fallthrough
Lookup the redirected path first (ie.
@ Fallback
Lookup the provided path first and if that fails, "fallback" to a lookup of the redirected path.
@ RedirectOnly
Only lookup the redirected path, do not lookup the originally provided path.
void setFallthrough(bool Fallthrough)
Sets the redirection kind to Fallthrough if true or RedirectOnly otherwise.
void visitChildFileSystems(VisitCallbackTy Callback) override
std::error_code getRealPath(const Twine &Path, SmallVectorImpl< char > &Output) override
Gets real path of Path e.g.
ErrorOr< std::unique_ptr< File > > openFileForRead(const Twine &Path) override
Get a File object for the text file at Path, if one exists.
void setOverlayFileDir(StringRef PrefixDir)
llvm::ErrorOr< std::string > getCurrentWorkingDirectory() const override
Get the working directory of this file system.
void setRedirection(RedirectingFileSystem::RedirectKind Kind)
std::error_code isLocal(const Twine &Path, bool &Result) override
Is the file mounted on a local filesystem?
static std::unique_ptr< RedirectingFileSystem > create(std::unique_ptr< MemoryBuffer > Buffer, SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath, void *DiagContext, IntrusiveRefCntPtr< FileSystem > ExternalFS)
Parses Buffer, which is expected to be in YAML format and returns a virtual file system representing ...
std::error_code setCurrentWorkingDirectory(const Twine &Path) override
Set the working directory.
StringRef getOverlayFileDir() const
void printEntry(raw_ostream &OS, Entry *E, unsigned IndentLevel=0) const
void getDirectoryContentRealSources(const Twine &Dir, SmallVectorImpl< std::string > &Out) override
Collect the paths in the real file system that contribute to a potentially virtual directory when ite...
The result of a status operation.
llvm::sys::fs::UniqueID getUniqueID() const
LLVM_ABI bool equivalent(const Status &Other) const
static LLVM_ABI Status copyWithNewName(const Status &In, const Twine &NewName)
Get a copy of a Status with a different name.
LLVM_ABI bool isStatusKnown() const
LLVM_ABI bool exists() const
bool ExposesExternalVFSPath
Whether this entity has an external path different from the virtual path, and the external path is ex...
uint32_t getGroup() const
static LLVM_ABI Status copyWithNewSize(const Status &In, uint64_t NewSize)
Get a copy of a Status with a different size.
LLVM_ABI bool isOther() const
LLVM_ABI bool isSymlink() const
llvm::sys::TimePoint getLastModificationTime() const
llvm::sys::fs::file_type getType() const
LLVM_ABI bool isRegularFile() const
LLVM_ABI bool isExecutable() const
Returns true if any of the owner, group, or others execute permissions is set.
LLVM_ABI bool isDirectory() const
LLVM_ABI void addFileMapping(StringRef VirtualPath, StringRef RealPath)
LLVM_ABI void write(llvm::raw_ostream &OS)
LLVM_ABI void addDirectoryMapping(StringRef VirtualPath, StringRef RealPath)
InMemoryDirectory(Status Stat)
InMemoryNode * addChild(StringRef Name, std::unique_ptr< InMemoryNode > Child)
Status getStatus(const Twine &RequestedName) const override
Return the Status for this node.
const_iterator end() const
static bool classof(const InMemoryNode *N)
InMemoryNode * getChild(StringRef Name) const
const_iterator begin() const
UniqueID getUniqueID() const
decltype(Entries)::const_iterator const_iterator
std::string toString(unsigned Indent) const override
Status getStatus(const Twine &RequestedName) const override
Return the Status for this node.
std::string toString(unsigned Indent) const override
InMemoryFile(Status Stat, std::unique_ptr< llvm::MemoryBuffer > Buffer)
static bool classof(const InMemoryNode *N)
llvm::MemoryBuffer * getBuffer() const
The in memory file system is a tree of Nodes.
StringRef getFileName() const
Get the filename of this node (the name without the directory part).
InMemoryNodeKind getKind() const
virtual ~InMemoryNode()=default
InMemoryNode(llvm::StringRef FileName, InMemoryNodeKind Kind)
virtual std::string toString(unsigned Indent) const =0
virtual Status getStatus(const Twine &RequestedName) const =0
Return the Status for this node.
A member of a directory, yielded by a directory_iterator.
llvm::StringRef path() const
llvm::sys::fs::file_type type() const
An input iterator over the entries in a virtual path, similar to llvm::sys::fs::directory_iterator.
directory_iterator & increment(std::error_code &EC)
Equivalent to operator++, with an error code.
An input iterator over the recursive contents of a virtual path, similar to llvm::sys::fs::recursive_...
recursive_directory_iterator()=default
Construct an 'end' iterator.
LLVM_ABI recursive_directory_iterator & increment(std::error_code &EC)
Equivalent to operator++, with an error code.
Abstract base class for all Nodes.
This class represents a YAML stream potentially containing multiple documents.
LLVM_ABI document_iterator end()
LLVM_ABI document_iterator begin()
LLVM_ABI void printError(Node *N, const Twine &Msg, SourceMgr::DiagKind Kind=SourceMgr::DK_Error)
Iterator abstraction for Documents over a Stream.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Resolved
Queried, materialization begun.
LLVM_ABI std::error_code closeFile(file_t &F)
Close the file object.
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
file_type
An enumeration for the file system's view of the type.
LLVM_ABI std::error_code getRealPathFromHandle(file_t Handle, SmallVectorImpl< char > &RealPath)
Get the real path of an open file from its handle.
LLVM_ABI std::error_code set_current_path(const Twine &path)
Set the current path.
LLVM_ABI std::error_code real_path(const Twine &path, SmallVectorImpl< char > &output, bool expand_tilde=false)
Collapse all .
LLVM_ABI Expected< file_t > openNativeFileForRead(const Twine &Name, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
LLVM_ABI std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
LLVM_ABI std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
LLVM_ABI std::error_code is_local(const Twine &path, bool &result)
Is the file mounted on a local filesystem?
LLVM_ABI std::error_code openFileForRead(const Twine &Name, int &ResultFD, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
LLVM_ABI bool is_directory(const basic_file_status &status)
Does status represent a directory?
LLVM_ABI StringRef get_separator(Style style=Style::native)
Return the preferred separator for this platform.
LLVM_ABI StringRef root_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get root path.
LLVM_ABI const_iterator begin(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get begin iterator over path.
LLVM_ABI bool remove_dots(SmallVectorImpl< char > &path, bool remove_dot_dot=false, Style style=Style::native)
Remove '.
LLVM_ABI StringRef parent_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get parent path.
LLVM_ABI void make_absolute(const Twine ¤t_directory, SmallVectorImpl< char > &path)
Make path an absolute path.
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
LLVM_ABI StringRef remove_leading_dotslash(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Remove redundant leading "./" pieces and consecutive separators.
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
LLVM_ABI reverse_iterator rend(StringRef path LLVM_LIFETIME_BOUND)
Get reverse end iterator over path.
LLVM_ABI reverse_iterator rbegin(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get reverse begin iterator over path.
LLVM_ABI const_iterator end(StringRef path LLVM_LIFETIME_BOUND)
Get end iterator over path.
LLVM_ABI bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
void violationIfEnabled()
ScopedSetting scopedDisable()
std::chrono::time_point< std::chrono::system_clock, D > TimePoint
A time point on the system clock.
TimePoint< std::chrono::seconds > toTimePoint(std::time_t T)
Convert a std::time_t to a TimePoint.
std::error_code make_error_code(OutputErrorCode EV)
LLVM_ABI void collectVFSEntries(RedirectingFileSystem &VFS, SmallVectorImpl< YAMLVFSEntry > &CollectedEntries)
Collect all pairs of <virtual path, real path> entries from the VFS.
LLVM_ABI std::unique_ptr< FileSystem > createPhysicalFileSystem()
Create an vfs::FileSystem for the 'real' file system, as seen by the operating system.
static sys::fs::UniqueID getFileID(sys::fs::UniqueID Parent, llvm::StringRef Name, llvm::StringRef Contents)
LLVM_ABI llvm::sys::fs::UniqueID getNextVirtualUniqueID()
Get a globally unique ID for a virtual file or directory.
static sys::fs::UniqueID getUniqueID(hash_code Hash)
LLVM_ABI std::optional< std::string > findFileInParentDirectories(FileSystem &FS, StringRef Dir, ArrayRef< StringRef > FileNames)
Searches Dir and then each of its parent directories for a regular file named one of FileNames,...
LLVM_ABI IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
LLVM_ABI std::unique_ptr< FileSystem > getVFSFromYAML(std::unique_ptr< llvm::MemoryBuffer > Buffer, llvm::SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath, void *DiagContext=nullptr, IntrusiveRefCntPtr< FileSystem > ExternalFS=getRealFileSystem())
Gets a FileSystem for a virtual file system described in YAML format.
static sys::fs::UniqueID getDirectoryID(sys::fs::UniqueID Parent, llvm::StringRef Name)
LLVM_ABI std::string escape(StringRef Input, bool EscapePrintable=true)
Escape Input for a double quoted scalar; if EscapePrintable is true, all UTF8 sequences will be escap...
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
IntrusiveRefCntPtr< T > makeIntrusiveRefCnt(Args &&...A)
Factory function for creating intrusive ref counted pointers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
@ no_such_file_or_directory
@ operation_not_permitted
auto reverse(ContainerTy &&C)
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
@ End
Run the machine verifier once, at the end of the pipeline.
LLVM_ABI std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
Implement std::hash so that hash_code can be used in STL containers.
static constexpr value_type Invalid
Value for an invalid file descriptor.
This class wraps the platform specific file handle/descriptor type to provide an unified representati...
bool isValid() const
Is a valid file.
Entry * E
The entry the looked-up path corresponds to.
LLVM_ABI LookupResult(Entry *E, sys::path::const_iterator Start, sys::path::const_iterator End)
LLVM_ABI void getPath(llvm::SmallVectorImpl< char > &Path) const
Get the (canonical) path of the found entry.
llvm::SmallVector< Entry *, 32 > Parents
Chain of parent directory entries for E.
An interface for virtual file systems to provide an iterator over the (non-recursive) contents of a d...
directory_entry CurrentEntry
LLVM_ABI Status makeStatus() const
llvm::sys::fs::file_type Type
std::unique_ptr< llvm::MemoryBuffer > Buffer
llvm::sys::fs::perms Perms
llvm::sys::fs::UniqueID DirUID