26 #include "llvm/Config/llvm-config.h" 52 #include <system_error> 67 : UID(Status.
getUniqueID()), MTime(Status.getLastModificationTime()),
68 User(Status.getUser()), Group(Status.getGroup()),
Size(Status.getSize()),
69 Type(Status.
type()), Perms(Status.permissions()) {}
74 : Name(Name.
str()), UID(UID), MTime(MTime), User(User), Group(Group),
75 Size(Size),
Type(
Type), Perms(Perms) {}
116 bool RequiresNullTerminator,
bool IsVolatile) {
121 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
128 auto WorkingDir = getCurrentWorkingDirectory();
130 return WorkingDir.getError();
172 class RealFile :
public File {
173 friend class RealFileSystem;
177 std::string RealName;
180 : FD(RawFD), S(NewName, {}, {}, {}, {}, {},
182 RealName(NewRealPathName.
str()) {
187 ~RealFile()
override;
193 bool RequiresNullTerminator,
195 std::error_code close()
override;
200 RealFile::~RealFile() { close(); }
204 if (!S.isStatusKnown()) {
214 return RealName.
empty() ? S.getName().str() : RealName;
218 RealFile::getBuffer(
const Twine &Name, int64_t FileSize,
219 bool RequiresNullTerminator,
bool IsVolatile) {
225 std::error_code RealFile::close() {
243 explicit RealFileSystem(
bool LinkCWDToProcess) {
244 if (!LinkCWDToProcess) {
260 std::error_code setCurrentWorkingDirectory(
const Twine &Path)
override;
261 std::error_code isLocal(
const Twine &Path,
bool &Result)
override;
262 std::error_code getRealPath(
const Twine &Path,
276 struct WorkingDirectory {
290 if (std::error_code EC =
303 return std::unique_ptr<File>(
304 new RealFile(*FDOrErr, Name.
str(), RealName.
str()));
309 return WD->Specified.str();
317 std::error_code RealFileSystem::setCurrentWorkingDirectory(
const Twine &Path) {
322 adjustPath(Path, Storage).toVector(Absolute);
331 return std::error_code();
334 std::error_code RealFileSystem::isLocal(
const Twine &Path,
bool &Result) {
340 RealFileSystem::getRealPath(
const Twine &Path,
352 return std::make_unique<RealFileSystem>(
false);
361 RealFSDirIter(
const Twine &Path, std::error_code &EC) : Iter(Path, EC) {
366 std::error_code increment()
override {
379 std::error_code &EC) {
382 std::make_shared<RealFSDirIter>(adjustPath(Dir, Storage), EC));
390 FSList.push_back(std::move(BaseFS));
394 FSList.push_back(FS);
402 for (
iterator I = overlays_begin(),
E = overlays_end();
I !=
E; ++
I) {
413 for (
iterator I = overlays_begin(),
E = overlays_end();
I !=
E; ++
I) {
414 auto Result = (*I)->openFileForRead(Path);
424 return FSList.front()->getCurrentWorkingDirectory();
429 for (
auto &
FS : FSList)
430 if (std::error_code EC =
FS->setCurrentWorkingDirectory(Path))
436 for (
auto &
FS : FSList)
437 if (
FS->exists(Path))
438 return FS->isLocal(Path, Result);
445 for (
auto &
FS : FSList)
446 if (
FS->exists(Path))
447 return FS->getRealPath(Path, Output);
462 std::error_code incrementFS() {
465 for (
auto E = Overlays.
overlays_end(); CurrentFS !=
E; ++CurrentFS) {
467 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
476 std::error_code incrementDirIter(
bool IsFirstTime) {
478 "incrementing past end");
487 std::error_code incrementImpl(
bool IsFirstTime) {
489 std::error_code EC = incrementDirIter(IsFirstTime);
494 CurrentEntry = *CurrentDirIter;
496 if (SeenNames.
insert(Name).second)
506 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
507 EC = incrementImpl(
true);
510 std::error_code increment()
override {
return incrementImpl(
false); }
516 std::error_code &EC) {
518 std::make_shared<OverlayFSDirIterImpl>(Dir, *
this, EC));
521 void ProxyFileSystem::anchor() {}
534 std::string FileName;
538 : Kind(Kind), FileName(
llvm::sys::path::
filename(FileName)) {}
544 virtual std::string
toString(
unsigned Indent)
const = 0;
549 std::unique_ptr<llvm::MemoryBuffer> Buffer;
554 Buffer(
std::move(Buffer)) {}
564 std::string
toString(
unsigned Indent)
const override {
565 return (std::string(Indent,
' ') + Stat.
getName() +
"\n").str();
580 :
InMemoryNode(Path, IME_HardLink), ResolvedFile(ResolvedFile) {}
581 const InMemoryFile &getResolvedFile()
const {
return ResolvedFile; }
583 std::string
toString(
unsigned Indent)
const override {
584 return std::string(Indent,
' ') +
"HardLink to -> " +
596 class InMemoryFileAdaptor :
public File {
599 std::string RequestedName;
603 std::string RequestedName)
604 : Node(Node), RequestedName(std::move(RequestedName)) {}
611 getBuffer(
const Twine &Name, int64_t FileSize,
bool RequiresNullTerminator,
612 bool IsVolatile)
override {
618 std::error_code close()
override {
return {}; }
637 auto I = Entries.
find(Name);
638 if (
I != Entries.
end())
639 return I->second.get();
644 return Entries.
insert(make_pair(Name, std::move(Child)))
645 .first->second.get();
653 std::string
toString(
unsigned Indent)
const override {
655 (std::string(Indent,
' ') + Stat.
getName() +
"\n").str();
656 for (
const auto &
Entry : Entries)
657 Result +=
Entry.second->toString(Indent + 2);
668 if (
auto Dir = dyn_cast<detail::InMemoryDirectory>(Node))
669 return Dir->getStatus(RequestedName);
670 if (
auto File = dyn_cast<detail::InMemoryFile>(Node))
671 return File->getStatus(RequestedName);
672 if (
auto Link = dyn_cast<detail::InMemoryHardLink>(Node))
673 return Link->getResolvedFile().getStatus(RequestedName);
680 : Root(new detail::InMemoryDirectory(
684 UseNormalizedPaths(UseNormalizedPaths) {}
689 return Root->toString(0);
692 bool InMemoryFileSystem::addFile(
const Twine &
P, time_t ModificationTime,
693 std::unique_ptr<llvm::MemoryBuffer> Buffer,
716 const auto ResolvedGroup = Group.
getValueOr(0);
719 assert(!(HardLinkTarget && Buffer) &&
"HardLink cannot have a buffer");
730 std::unique_ptr<detail::InMemoryNode> Child;
732 Child.reset(
new detail::InMemoryHardLink(P.
str(), *HardLinkTarget));
737 ResolvedGroup, Buffer->getBufferSize(), ResolvedType,
746 Dir->
addChild(Name, std::move(Child));
756 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
757 Name, std::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
761 if (
auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
764 assert((isa<detail::InMemoryFile>(Node) ||
765 isa<detail::InMemoryHardLink>(Node)) &&
766 "Must be either file, hardlink or directory!");
773 if (
auto Link = dyn_cast<detail::InMemoryHardLink>(Node)) {
774 return Link->getResolvedFile().getBuffer()->getBuffer() ==
777 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
783 bool InMemoryFileSystem::addFile(
const Twine &P, time_t ModificationTime,
784 std::unique_ptr<llvm::MemoryBuffer> Buffer,
789 return addFile(P, ModificationTime, std::move(Buffer), User, Group, Type,
799 return addFile(P, ModificationTime,
802 std::move(User), std::move(Group), std::move(Type),
831 if (
auto File = dyn_cast<detail::InMemoryFile>(Node)) {
838 if (
auto File = dyn_cast<detail::InMemoryHardLink>(Node)) {
840 return &
File->getResolvedFile();
844 Dir = cast<detail::InMemoryDirectory>(Node);
851 const Twine &ToPath) {
856 if (!ToNode || FromNode || !isa<detail::InMemoryFile>(*ToNode))
859 cast<detail::InMemoryFile>(*ToNode));
865 return detail::getNodeStatus(*Node, Path);
866 return Node.getError();
873 return Node.getError();
877 if (
auto *
F = dyn_cast<detail::InMemoryFile>(*Node))
878 return std::unique_ptr<File>(
879 new detail::InMemoryFileAdaptor(*
F, Path.
str()));
891 std::string RequestedDirName;
893 void setCurrentEntry() {
898 switch (I->second->getKind()) {
916 InMemoryDirIterator() =
default;
919 std::string RequestedDirName)
921 RequestedDirName(std::move(RequestedDirName)) {
925 std::error_code increment()
override {
935 std::error_code &EC) {
938 EC = Node.getError();
942 if (
auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
944 std::make_shared<InMemoryDirIterator>(*DirNode, Dir.
str()));
963 WorkingDirectory = Path.
str();
971 if (!CWD || CWD->empty())
993 : ExternalFS(std::move(FS)) {
995 if (
auto ExternalWorkingDirectory =
996 ExternalFS->getCurrentWorkingDirectory()) {
997 WorkingDirectory = *ExternalWorkingDirectory;
998 ExternalFSValidWD =
true;
1016 bool IterateExternalFS;
1018 bool IsExternalFSCurrent =
false;
1029 std::error_code incrementImpl(
bool IsFirstTime);
1031 std::error_code incrementContent(
bool IsFirstTime);
1033 std::error_code incrementExternal();
1041 bool IterateExternalFS,
FileSystem &ExternalFS, std::error_code &EC);
1043 std::error_code increment()
override;
1048 return WorkingDirectory;
1059 auto EC = ExternalFS->setCurrentWorkingDirectory(Path);
1060 ExternalFSValidWD = !
static_cast<bool>(EC);
1067 WorkingDirectory = AbsolutePath.
str();
1073 return ExternalFS->isLocal(Path, Result);
1083 return WorkingDir.getError();
1090 std::error_code &EC) {
1095 return ExternalFS->dir_begin(Dir, EC);
1103 if (!S->isDirectory()) {
1105 std::system_category());
1109 auto *
D = cast<RedirectingFileSystem::RedirectingDirectoryEntry>(*E);
1111 Dir,
D->contents_begin(),
D->contents_end(),
1112 shouldUseExternalFS(), *ExternalFS, EC));
1116 ExternalContentsPrefixDir = PrefixDir.
str();
1120 return ExternalContentsPrefixDir;
1124 for (
const auto &Root : Roots)
1125 dumpEntry(OS, Root.get());
1130 int NumSpaces)
const {
1132 for (
int i = 0,
e = NumSpaces; i <
e; ++i)
1134 OS <<
"'" << Name.
str().c_str() <<
"'" 1139 assert(DE &&
"Should be a directory");
1141 for (std::unique_ptr<Entry> &SubEntry :
1143 dumpEntry(OS, SubEntry.get(), NumSpaces + 2);
1147 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1163 error(N,
"expected string");
1166 Result = S->getValue(Storage);
1171 bool parseScalarBool(
yaml::Node *N,
bool &Result) {
1174 if (!parseScalarString(N, Value, Storage))
1187 error(N,
"expected boolean value");
1195 KeyStatus(
bool Required =
false) :
Required(Required) {}
1198 using KeyStatusPair = std::pair<StringRef, KeyStatus>;
1203 if (!Keys.
count(Key)) {
1204 error(KeyNode,
"unknown key");
1207 KeyStatus &S = Keys[
Key];
1209 error(KeyNode,
Twine(
"duplicate key '") + Key +
"'");
1218 for (
const auto &
I : Keys) {
1219 if (
I.second.Required && !
I.second.Seen) {
1220 error(Obj,
Twine(
"missing key '") +
I.first +
"'");
1231 for (
const auto &Root : FS->Roots) {
1232 if (Name.
equals(Root->getName())) {
1233 ParentEntry = Root.get();
1240 for (std::unique_ptr<RedirectingFileSystem::Entry> &Content :
1245 if (DirContent && Name.
equals(Content->getName()))
1251 std::unique_ptr<RedirectingFileSystem::Entry>
E =
1252 std::make_unique<RedirectingFileSystem::RedirectingDirectoryEntry>(
1258 FS->Roots.push_back(std::move(E));
1259 ParentEntry = FS->Roots.back().get();
1264 cast<RedirectingFileSystem::RedirectingDirectoryEntry>(ParentEntry);
1265 DE->addContent(std::move(E));
1266 return DE->getLastContent();
1275 auto *DE = cast<RedirectingFileSystem::RedirectingDirectoryEntry>(SrcE);
1280 NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1281 for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
1283 uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1287 assert(NewParentE &&
"Parent entry must exist");
1288 auto *FE = cast<RedirectingFileSystem::RedirectingFileEntry>(SrcE);
1290 cast<RedirectingFileSystem::RedirectingDirectoryEntry>(NewParentE);
1292 std::make_unique<RedirectingFileSystem::RedirectingFileEntry>(
1293 Name, FE->getExternalContentsPath(), FE->getUseName()));
1299 std::unique_ptr<RedirectingFileSystem::Entry>
1303 error(N,
"expected mapping node for file or directory entry");
1307 KeyStatusPair Fields[] = {
1308 KeyStatusPair(
"name",
true),
1309 KeyStatusPair(
"type",
true),
1310 KeyStatusPair(
"contents",
false),
1311 KeyStatusPair(
"external-contents",
false),
1312 KeyStatusPair(
"use-external-name",
false),
1317 bool HasContents =
false;
1318 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>>
1320 std::string ExternalContentsPath;
1323 auto UseExternalName =
1327 for (
auto &
I : *M) {
1332 if (!parseScalarString(
I.getKey(),
Key, Buffer))
1335 if (!checkDuplicateOrUnknownKey(
I.getKey(),
Key, Keys))
1339 if (Key ==
"name") {
1340 if (!parseScalarString(
I.getValue(),
Value, Buffer))
1343 NameValueNode =
I.getValue();
1344 if (FS->UseCanonicalizedPaths) {
1354 }
else if (Key ==
"type") {
1355 if (!parseScalarString(
I.getValue(),
Value, Buffer))
1357 if (Value ==
"file")
1359 else if (Value ==
"directory")
1362 error(
I.getValue(),
"unknown value for 'type'");
1365 }
else if (Key ==
"contents") {
1368 "entry already has 'contents' or 'external-contents'");
1375 error(
I.getValue(),
"expected array");
1379 for (
auto &
I : *Contents) {
1380 if (std::unique_ptr<RedirectingFileSystem::Entry>
E =
1381 parseEntry(&
I, FS,
false))
1382 EntryArrayContents.push_back(std::move(
E));
1386 }
else if (Key ==
"external-contents") {
1389 "entry already has 'contents' or 'external-contents'");
1393 if (!parseScalarString(
I.getValue(),
Value, Buffer))
1397 if (FS->IsRelativeOverlay) {
1400 "External contents prefix directory must exist");
1406 if (FS->UseCanonicalizedPaths) {
1412 ExternalContentsPath = FullPath.
str();
1413 }
else if (Key ==
"use-external-name") {
1415 if (!parseScalarBool(
I.getValue(), Val))
1430 error(N,
"missing key 'contents' or 'external-contents'");
1433 if (!checkMissingKeys(N, Keys))
1440 error(N,
"'use-external-name' is not supported for directories");
1453 assert(NameValueNode &&
"Name presence should be checked earlier");
1454 error(NameValueNode,
1455 "entry with relative path at the root level is not discoverable");
1463 while (Trimmed.
size() > RootPathLen &&
1465 Trimmed = Trimmed.
slice(0, Trimmed.
size() - 1);
1470 std::unique_ptr<RedirectingFileSystem::Entry> Result;
1473 Result = std::make_unique<RedirectingFileSystem::RedirectingFileEntry>(
1474 LastComponent, std::move(ExternalContentsPath), UseExternalName);
1478 std::make_unique<RedirectingFileSystem::RedirectingDirectoryEntry>(
1479 LastComponent, std::move(EntryArrayContents),
1494 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> Entries;
1495 Entries.push_back(std::move(Result));
1497 std::make_unique<RedirectingFileSystem::RedirectingDirectoryEntry>(
1498 *
I, std::move(Entries),
1513 error(Root,
"expected mapping node");
1517 KeyStatusPair Fields[] = {
1518 KeyStatusPair(
"version",
true),
1519 KeyStatusPair(
"case-sensitive",
false),
1520 KeyStatusPair(
"use-external-names",
false),
1521 KeyStatusPair(
"overlay-relative",
false),
1522 KeyStatusPair(
"fallthrough",
false),
1523 KeyStatusPair(
"roots",
true),
1527 std::vector<std::unique_ptr<RedirectingFileSystem::Entry>> RootEntries;
1530 for (
auto &
I : *Top) {
1533 if (!parseScalarString(
I.getKey(),
Key, KeyBuffer))
1536 if (!checkDuplicateOrUnknownKey(
I.getKey(),
Key, Keys))
1539 if (Key ==
"roots") {
1542 error(
I.getValue(),
"expected array");
1546 for (
auto &
I : *Roots) {
1547 if (std::unique_ptr<RedirectingFileSystem::Entry>
E =
1548 parseEntry(&
I, FS,
true))
1549 RootEntries.push_back(std::move(
E));
1553 }
else if (Key ==
"version") {
1556 if (!parseScalarString(
I.getValue(), VersionString, Storage))
1560 error(
I.getValue(),
"expected integer");
1564 error(
I.getValue(),
"invalid version number");
1568 error(
I.getValue(),
"version mismatch, expected 0");
1571 }
else if (Key ==
"case-sensitive") {
1572 if (!parseScalarBool(
I.getValue(), FS->CaseSensitive))
1574 }
else if (Key ==
"overlay-relative") {
1575 if (!parseScalarBool(
I.getValue(), FS->IsRelativeOverlay))
1577 }
else if (Key ==
"use-external-names") {
1578 if (!parseScalarBool(
I.getValue(), FS->UseExternalNames))
1580 }
else if (Key ==
"fallthrough") {
1581 if (!parseScalarBool(
I.getValue(), FS->IsFallthrough))
1591 if (!checkMissingKeys(Top, Keys))
1597 for (
auto &
E : RootEntries)
1598 uniqueOverlayTree(FS,
E.get());
1607 StringRef YAMLFilePath,
void *DiagContext,
1615 if (DI == Stream.end() || !Root) {
1622 std::unique_ptr<RedirectingFileSystem>
FS(
1625 if (!YAMLFilePath.
empty()) {
1636 assert(!EC &&
"Overlay dir final path must be absolute");
1638 FS->setExternalContentsPrefixDir(OverlayAbsDir);
1641 if (!P.
parse(Root, FS.get()))
1644 return FS.release();
1648 RedirectingFileSystem::lookupPath(
const Twine &Path_)
const {
1659 if (UseCanonicalizedPaths) {
1669 for (
const auto &Root : Roots) {
1671 lookupPath(Start, End, Root.get());
1685 "Paths should not contain traversal components");
1689 if (Start->equals(
"."))
1696 if (!FromName.
empty()) {
1697 if (!pathComponentMatches(*Start, FromName))
1712 for (
const std::unique_ptr<RedirectingFileSystem::Entry> &DirEntry :
1715 lookupPath(Start, End, DirEntry.get());
1725 Status S = ExternalStatus;
1726 if (!UseExternalNames)
1735 if (
auto *
F = dyn_cast<RedirectingFileSystem::RedirectingFileEntry>(E)) {
1737 assert(!S || S->getName() ==
F->getExternalContentsPath());
1743 auto *DE = cast<RedirectingFileSystem::RedirectingDirectoryEntry>(
E);
1751 if (shouldUseExternalFS() &&
1753 return ExternalFS->status(Path);
1757 return status(Path, *Result);
1763 class FileWithFixedStatus :
public File {
1764 std::unique_ptr<File> InnerFile;
1768 FileWithFixedStatus(std::unique_ptr<File> InnerFile,
Status S)
1769 : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
1774 getBuffer(
const Twine &Name, int64_t FileSize,
bool RequiresNullTerminator,
1775 bool IsVolatile)
override {
1776 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1780 std::error_code close()
override {
return InnerFile->close(); }
1789 if (shouldUseExternalFS() &&
1791 return ExternalFS->openFileForRead(Path);
1800 auto Result = ExternalFS->openFileForRead(
F->getExternalContentsPath());
1804 auto ExternalStatus = (*Result)->status();
1805 if (!ExternalStatus)
1806 return ExternalStatus.getError();
1811 return std::unique_ptr<File>(
1812 std::make_unique<FileWithFixedStatus>(std::move(*Result), S));
1820 if (shouldUseExternalFS() &&
1822 return ExternalFS->getRealPath(Path, Output);
1828 dyn_cast<RedirectingFileSystem::RedirectingFileEntry>(*Result)) {
1829 return ExternalFS->getRealPath(
F->getExternalContentsPath(), Output);
1833 return shouldUseExternalFS() ? ExternalFS->getRealPath(Path, Output)
1840 StringRef YAMLFilePath,
void *DiagContext,
1843 YAMLFilePath, DiagContext,
1844 std::move(ExternalFS));
1853 assert(DE &&
"Must be a directory");
1854 for (std::unique_ptr<RedirectingFileSystem::Entry> &SubEntry :
1865 assert(FE &&
"Must be a file");
1867 for (
auto &Comp : Path)
1879 std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
1880 std::move(ExternalFS));
1890 static std::atomic<unsigned> UID;
1891 unsigned ID = ++UID;
1901 Mappings.emplace_back(VirtualPath, RealPath);
1910 unsigned getDirIndent() {
return 4 * DirStack.
size(); }
1911 unsigned getFileIndent() {
return 4 * (DirStack.
size() + 1); }
1915 void endDirectory();
1934 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1935 if (*IParent != *IChild)
1939 return IParent == EParent;
1944 assert(containedIn(Parent, Path));
1948 void JSONWriter::startDirectory(
StringRef Path) {
1950 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1951 DirStack.push_back(Path);
1952 unsigned Indent = getDirIndent();
1953 OS.indent(Indent) <<
"{\n";
1954 OS.indent(Indent + 2) <<
"'type': 'directory',\n";
1956 OS.indent(Indent + 2) <<
"'contents': [\n";
1959 void JSONWriter::endDirectory() {
1960 unsigned Indent = getDirIndent();
1961 OS.indent(Indent + 2) <<
"]\n";
1962 OS.indent(Indent) <<
"}";
1964 DirStack.pop_back();
1968 unsigned Indent = getFileIndent();
1969 OS.indent(Indent) <<
"{\n";
1970 OS.indent(Indent + 2) <<
"'type': 'file',\n";
1972 OS.indent(Indent + 2) <<
"'external-contents': \"" 1974 OS.indent(Indent) <<
"}";
1987 OS <<
" 'case-sensitive': '" 1988 << (IsCaseSensitive.
getValue() ?
"true" :
"false") <<
"',\n";
1990 OS <<
" 'use-external-names': '" 1991 << (UseExternalNames.
getValue() ?
"true" :
"false") <<
"',\n";
1992 bool UseOverlayRelative =
false;
1993 if (IsOverlayRelative.
hasValue()) {
1994 UseOverlayRelative = IsOverlayRelative.
getValue();
1995 OS <<
" 'overlay-relative': '" << (UseOverlayRelative ?
"true" :
"false")
1998 OS <<
" 'roots': [\n";
2000 if (!Entries.
empty()) {
2005 if (UseOverlayRelative) {
2006 unsigned OverlayDirLen = OverlayDir.
size();
2008 "Overlay dir must be contained in RPath");
2009 RPath = RPath.
slice(OverlayDirLen, RPath.size());
2014 for (
const auto &Entry : Entries.
slice(1)) {
2016 if (Dir == DirStack.
back())
2019 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
2024 startDirectory(Dir);
2027 if (UseOverlayRelative) {
2028 unsigned OverlayDirLen = OverlayDir.
size();
2030 "Overlay dir must be contained in RPath");
2031 RPath = RPath.
slice(OverlayDirLen, RPath.size());
2036 while (!DirStack.empty()) {
2052 JSONWriter(OS).write(
Mappings, UseExternalNames, IsCaseSensitive,
2053 IsOverlayRelative, OverlayDir);
2060 bool IterateExternalFS,
FileSystem &ExternalFS, std::error_code &EC)
2061 : Dir(_Path.str()), Current(Begin), End(End),
2062 IterateExternalFS(IterateExternalFS), ExternalFS(ExternalFS) {
2063 EC = incrementImpl(
true);
2067 return incrementImpl(
false);
2070 std::error_code VFSFromYamlDirIterImpl::incrementExternal() {
2072 "incrementing past end");
2074 if (IsExternalFSCurrent) {
2076 }
else if (IterateExternalFS) {
2077 ExternalDirIter = ExternalFS.dir_begin(Dir, EC);
2078 IsExternalFSCurrent =
true;
2091 std::error_code VFSFromYamlDirIterImpl::incrementContent(
bool IsFirstTime) {
2092 assert((IsFirstTime || Current != End) &&
"cannot iterate past end");
2095 while (Current != End) {
2099 switch ((*Current)->getKind()) {
2110 return incrementExternal();
2113 std::error_code VFSFromYamlDirIterImpl::incrementImpl(
bool IsFirstTime) {
2115 std::error_code EC = IsExternalFSCurrent ? incrementExternal()
2116 : incrementContent(IsFirstTime);
2120 if (SeenNames.
insert(Name).second)
2131 State = std::make_shared<detail::RecDirIterState>();
2132 State->Stack.push(I);
2138 assert(FS && State && !State->Stack.empty() &&
"incrementing past end");
2139 assert(!State->Stack.top()->path().empty() &&
"non-canonical end iterator");
2142 if (State->HasNoPushRequest)
2143 State->HasNoPushRequest =
false;
2148 State->Stack.push(I);
2154 while (!State->Stack.empty() && State->Stack.top().increment(EC) == End)
2157 if (State->Stack.empty())
An input iterator over the recursive contents of a virtual path, similar to llvm::sys::fs::recursive_...
const file_t kInvalidFile
const T & front() const
front - Get the first element.
virtual StringRef getBufferIdentifier() const
Return an identifier for this buffer, typically the filename it was read from.
A file system that allows overlaying one AbstractFileSystem on top of another.
static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames, Status ExternalStatus)
iterator overlays_begin()
Get an iterator pointing to the most recently added file system.
bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
llvm::MemoryBuffer * getBuffer() const
An interface for virtual file systems to provide an iterator over the (non-recursive) contents of a d...
const_iterator end(StringRef path)
Get end iterator over path.
llvm::StringRef path() const
Represents either an error or a value T.
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
InMemoryNode * getChild(StringRef Name)
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
StringRef getBuffer() const
std::string toString(unsigned Indent) const override
This class represents lattice values for constants.
InMemoryDirectory(Status Stat)
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.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
~InMemoryFileSystem() override
FileSystemList::reverse_iterator iterator
LLVM_NODISCARD bool equals_lower(StringRef RHS) const
equals_lower - Check for string equality, ignoring case.
constexpr char IsVolatile[]
Key for Kernel::Arg::Metadata::mIsVolatile.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
Status getStatus(const Twine &RequestedName) const
Return the Status for this node.
llvm::sys::fs::UniqueID getNextVirtualUniqueID()
Get a globally unique ID for a virtual file or directory.
std::error_code setCurrentWorkingDirectory(const Twine &Path) override
Set the working directory.
void push_back(const T &Elt)
perms permissions() const
static void getVFSEntries(RedirectingFileSystem::Entry *SrcE, SmallVectorImpl< StringRef > &Path, SmallVectorImpl< YAMLVFSEntry > &Entries)
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
RedirectingFileSystemParser(yaml::Stream &S)
std::error_code setCurrentWorkingDirectory(const Twine &Path) override
Set the working directory.
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
constexpr T getValueOr(U &&value) const LLVM_LVALUE_FUNCTION
Represents a YAML sequence created from either a block sequence for a flow sequence.
iterator find(StringRef Key)
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(const Twine &Name, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
This is a convenience method that opens a file, gets its content and then closes the file...
EntryKind getKind() const
std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
The result of a status operation.
bool is_directory(const basic_file_status &status)
Does status represent a directory?
The in memory file system is a tree of Nodes.
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...
StringRef remove_leading_dotslash(StringRef path, Style style=Style::native)
Remove redundant leading "./" pieces and consecutive separators.
Error takeError()
Take ownership of the stored error.
directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override
Get a directory_iterator for Dir.
Represents the result of a call to sys::fs::status().
void dumpEntry(raw_ostream &OS, Entry *E, int NumSpaces=0) const
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
void PrintMessage(raw_ostream &OS, SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges=None, ArrayRef< SMFixIt > FixIts=None, bool ShowColors=true) const
Emit a message about the specified location with the specified string.
std::string toString(Error E)
Write all error messages (if any) in E to a string.
reverse_iterator rbegin(StringRef path, Style style=Style::native)
Get reverse begin iterator over path.
InMemoryFileSystem(bool UseNormalizedPaths=true)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override
Get a directory_iterator for Dir.
void write(llvm::raw_ostream &OS)
void make_absolute(const Twine ¤t_directory, SmallVectorImpl< char > &path)
Make path an absolute path.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getOpenFile(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, bool RequiresNullTerminator=true, bool IsVolatile=false)
Given an already-open file descriptor, read the file and return a MemoryBuffer.
std::error_code getRealPath(const Twine &Path, SmallVectorImpl< char > &Output) const override
Canonicalizes Path by combining with the current working directory and normalizing the path (e...
std::error_code make_error_code(BitcodeError E)
static StringRef getName(Value *V)
bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
recursive_directory_iterator & increment(std::error_code &EC)
Equivalent to operator++, with an error code.
StringRef getName() const
Returns the name that should be used for this file or directory.
static Status copyWithNewName(const Status &In, const Twine &NewName)
Get a copy of a Status with a different name.
llvm::ErrorOr< Status > status(const Twine &Path) override
Get the status of the entry at Path, if one exists.
LLVM_NODISCARD StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
std::error_code isLocal(const Twine &Path, bool &Result) override
Is the file mounted on a local filesystem?
Tagged union holding either a T or a Error.
StringRef root_path(StringRef path, Style style=Style::native)
Get root path.
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
static void DiagHandler(const SMDiagnostic &Diag, void *Context)
InMemoryNode(llvm::StringRef FileName, InMemoryNodeKind Kind)
StringRef str() const
Explicit conversion to StringRef.
static bool classof(const InMemoryNode *N)
virtual std::error_code makeAbsolute(SmallVectorImpl< char > &Path) const
Make Path an absolute path.
const T & getValue() const LLVM_LVALUE_FUNCTION
virtual std::error_code getRealPath(const Twine &Path, SmallVectorImpl< char > &Output) const
Gets real path of Path e.g.
bool exists(const Twine &Path)
Check whether a file exists. Provided for convenience.
directory_entry CurrentEntry
llvm::ErrorOr< std::string > getCurrentWorkingDirectory() const override
Get the working directory of this file system.
std::error_code is_local(const Twine &path, bool &result)
Is the file mounted on a local filesystem?
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
LLVM_NODISCARD size_t size() const
size - Get the string size.
directory_iterator & increment(std::error_code &EC)
Equivalent to operator++, with an error code.
InMemoryNode * addChild(StringRef Name, std::unique_ptr< InMemoryNode > Child)
llvm::sys::fs::file_type getType() const
llvm::ErrorOr< std::string > getCurrentWorkingDirectory() const override
Get the working directory of this file system.
std::error_code setCurrentWorkingDirectory(const Twine &Path) override
Set the working directory.
std::error_code isLocal(const Twine &Path, bool &Result) override
Is the file mounted on a local filesystem?
void addFileMapping(StringRef VirtualPath, StringRef RealPath)
std::error_code real_path(const Twine &path, SmallVectorImpl< char > &output, bool expand_tilde=false)
Collapse all .
virtual std::error_code isLocal(const Twine &Path, bool &Result)
Is the file mounted on a local filesystem?
llvm::sys::TimePoint getLastModificationTime() const
void setDiagHandler(DiagHandlerTy DH, void *Ctx=nullptr)
Specify a diagnostic handler to be invoked every time PrintMessage is called.
bool isRegularFile() const
A virtual file system parsed from a YAML file.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
static 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 ...
The instances of the Type class are immutable: once they are created, they are never changed...
void printError(Node *N, const Twine &Msg)
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
UniqueID getUniqueID() const
std::error_code getRealPath(const Twine &Path, SmallVectorImpl< char > &Output) const override
Gets real path of Path e.g.
Instrumentation for Order File
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
llvm::ErrorOr< Status > status(const Twine &Path) override
Get the status of the entry at Path, if one exists.
static bool classof(const InMemoryNode *N)
const_iterator end() const
std::error_code getError() const
llvm::sys::fs::perms getPermissions() const
TimePoint getLastModificationTime() const
The file modification time as reported from the underlying file system.
virtual std::error_code setCurrentWorkingDirectory(const Twine &Path)=0
Set the working directory.
bool addHardLink(const Twine &From, const Twine &To)
Add a hard link to a file.
static sys::TimePoint< std::chrono::seconds > now(bool Deterministic)
InMemoryFile(Status Stat, std::unique_ptr< llvm::MemoryBuffer > Buffer)
static bool pathHasTraversal(StringRef Path)
static ErrorOr< const detail::InMemoryNode * > lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir, const Twine &P)
std::unique_ptr< FileSystem > createPhysicalFileSystem()
Create an vfs::FileSystem for the 'real' file system, as seen by the operating system.
std::error_code getUniqueID(const Twine Path, UniqueID &Result)
static bool isTraversalComponent(StringRef Component)
std::error_code isLocal(const Twine &Path, bool &Result) override
Is the file mounted on a local filesystem?
A single file or directory in the VFS.
StringRef parent_path(StringRef path, Style style=Style::native)
Get parent path.
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling...
void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
void(*)(const SMDiagnostic &, void *Context) DiagHandlerTy
Clients that want to handle their own diagnostics in a custom way can register a function pointer+con...
static void write(bool isBE, void *P, T V)
bool isStatusKnown() const
LLVM_NODISCARD char back() const
back - Get the last character in the string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
A member of a directory, yielded by a directory_iterator.
std::pair< typename base::iterator, bool > insert(StringRef Key)
A scalar node is an opaque datum that can be presented as a series of zero or more Unicode scalar val...
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
virtual ~File()
Destroy the file after closing it (if open).
const_iterator begin() const
void sort(IteratorTy Start, IteratorTy End)
std::string toString() const
ErrorOr< std::unique_ptr< File > > openFileForRead(const Twine &Path) override
Get a File object for the file at Path, if one exists.
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
BlockVerifier::State From
bool useNormalizedPaths() const
Return true if this file system normalizes . and .. in paths.
An input iterator over the entries in a virtual path, similar to llvm::sys::fs::directory_iterator.
Align max(MaybeAlign Lhs, Align Rhs)
VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem::RedirectingDirectoryEntry::iterator Begin, RedirectingFileSystem::RedirectingDirectoryEntry::iterator End, bool IterateExternalFS, FileSystem &ExternalFS, std::error_code &EC)
std::error_code makeAbsolute(SmallVectorImpl< char > &Path) const override
Make Path an absolute path.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
This class represents a YAML stream potentially containing multiple documents.
bool remove_dots(SmallVectorImpl< char > &path, bool remove_dot_dot=false, Style style=Style::native)
In-place remove any '.
bool equivalent(const Status &Other) const
The virtual file system interface.
OverlayFileSystem(IntrusiveRefCntPtr< FileSystem > Base)
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.
std::string toString(unsigned Indent) const override
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
std::error_code closeFile(file_t &F)
Close the file object.
virtual directory_iterator dir_begin(const Twine &Dir, std::error_code &EC)=0
Get a directory_iterator for Dir.
StringRef getExternalContentsPrefixDir() const
recursive_directory_iterator()=default
Construct an 'end' iterator.
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
This interface provides simple read-only access to a block of memory, and provides simple methods for...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
llvm::ErrorOr< std::unique_ptr< File > > openFileForRead(const Twine &Path) override
Get a File object for the file at Path, if one exists.
uint32_t getGroup() const
uint32_t getGroup() const
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
InMemoryNodeKind getKind() const
An in-memory file system.
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...
std::error_code set_current_path(const Twine &path)
Set the current path.
LLVM_NODISCARD bool equals(StringRef RHS) const
equals - Check for string equality, this is more efficient than compare() when the relative ordering ...
Defines the virtual file system interface vfs::FileSystem.
IntrusiveRefCntPtr< 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.
directory_iterator - Iterates through the entries in path.
Provides a library for accessing information about this process and other processes on the operating ...
file_type
An enumeration for the file system's view of the type.
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override
Get a directory_iterator for Dir.
LLVM_NODISCARD bool empty() const
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Represents a YAML map created from either a block map for a flow map.
void pushOverlay(IntrusiveRefCntPtr< FileSystem > FS)
Pushes a file system on top of the stack.
reverse_iterator rend(StringRef path)
Get reverse end iterator over path.
llvm::ErrorOr< std::unique_ptr< File > > openFileForRead(const Twine &Path) override
Get a File object for the file at Path, if one exists.
StringRef getFileName() const
Get the filename of this node (the name without the directory part).
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::string str() const
Return the twine contents as a std::string.
void setExternalContentsPrefixDir(StringRef PrefixDir)
Provides ErrorOr<T> smart pointer.
std::error_code increment() override
Sets CurrentEntry to the next entry in the directory on success, to directory_entry() at end...
Status getStatus(const Twine &RequestedName) const
Return the Status for this node.
Iterator abstraction for Documents over a Stream.
void collectVFSFromYAML(std::unique_ptr< llvm::MemoryBuffer > Buffer, llvm::SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath, SmallVectorImpl< YAMLVFSEntry > &CollectedEntries, void *DiagContext=nullptr, IntrusiveRefCntPtr< FileSystem > ExternalFS=getRealFileSystem())
Collect all pairs of <virtual path, real path> entries from the YAMLFilePath.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A helper class to hold the common YAML parsing state.
llvm::ErrorOr< std::string > getCurrentWorkingDirectory() const override
Get the working directory of this file system.
LLVM_DUMP_METHOD void dump() const
bool addFileNoOwn(const Twine &Path, time_t ModificationTime, llvm::MemoryBuffer *Buffer, Optional< uint32_t > User=None, Optional< uint32_t > Group=None, Optional< llvm::sys::fs::file_type > Type=None, Optional< llvm::sys::fs::perms > Perms=None)
Add a buffer to the VFS with a path.
llvm::sys::fs::UniqueID getUniqueID() const
StringSet - A wrapper for StringMap that provides set-like functionality.
This class implements an extremely fast bulk output stream that can only output to a stream...
decltype(Entries)::const_iterator const_iterator
StringRef - Represent a constant reference to a string, i.e.
decltype(Contents)::iterator iterator
std::error_code getRealPath(const Twine &Path, SmallVectorImpl< char > &Output) const override
Gets real path of Path e.g.
StringRef getName() const
Represents a location in source code.
iterator overlays_end()
Get an iterator pointing one-past the least recently added file system.
std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
TimePoint< std::chrono::seconds > toTimePoint(std::time_t T)
Convert a std::time_t to a TimePoint.
bool empty() const
empty - Check if the array is empty.
std::chrono::time_point< std::chrono::system_clock, D > TimePoint
A time point on the system clock.
Abstract base class for all Nodes.
bool parse(yaml::Node *Root, RedirectingFileSystem *FS)