14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/StringSet.h"
18 #include "llvm/ADT/iterator_range.h"
19 #include "llvm/Config/llvm-config.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Errc.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/Path.h"
24 #include "llvm/Support/Process.h"
25 #include "llvm/Support/YAMLParser.h"
37 using namespace clang;
38 using namespace clang::vfs;
40 using llvm::sys::fs::file_status;
41 using llvm::sys::fs::file_type;
42 using llvm::sys::fs::perms;
43 using llvm::sys::fs::UniqueID;
46 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
47 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
48 Type(Status.
type()), Perms(Status.permissions()), IsVFSMapped(
false) {}
50 Status::Status(StringRef
Name, UniqueID UID, sys::TimeValue MTime,
51 uint32_t User, uint32_t Group, uint64_t Size, file_type
Type,
53 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
54 Type(Type), Perms(Perms), IsVFSMapped(
false) {}
56 Status Status::copyWithNewName(
const Status &In, StringRef NewName) {
63 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
64 In.getUser(), In.getGroup(), In.getSize(), In.type(),
72 return Type == file_type::directory_file;
75 return Type == file_type::regular_file;
81 return Type == file_type::symlink_file;
84 return Type != file_type::status_error;
94 ErrorOr<std::unique_ptr<MemoryBuffer>>
96 bool RequiresNullTerminator,
bool IsVolatile) {
101 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
105 if (llvm::sys::path::is_absolute(Path))
106 return std::error_code();
110 return WorkingDir.getError();
112 return llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
122 return Component.equals(
"..") || Component.equals(
".");
126 using namespace llvm::sys;
140 class RealFile :
public File {
143 std::string RealName;
144 friend class RealFileSystem;
145 RealFile(
int FD, StringRef NewName, StringRef NewRealPathName)
146 : FD(FD),
S(NewName, {}, {}, {}, {}, {},
147 llvm::sys::fs::file_type::status_error, {}),
148 RealName(NewRealPathName.str()) {
149 assert(FD >= 0 &&
"Invalid or inactive file descriptor");
153 ~RealFile()
override;
154 ErrorOr<Status> status()
override;
155 ErrorOr<std::string> getName()
override;
156 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(
const Twine &
Name,
158 bool RequiresNullTerminator,
159 bool IsVolatile)
override;
160 std::error_code close()
override;
163 RealFile::~RealFile() { close(); }
165 ErrorOr<Status> RealFile::status() {
166 assert(FD != -1 &&
"cannot stat closed file");
167 if (!
S.isStatusKnown()) {
168 file_status RealStatus;
169 if (std::error_code EC = sys::fs::status(FD, RealStatus))
176 ErrorOr<std::string> RealFile::getName() {
177 return RealName.empty() ?
S.getName().str() : RealName;
180 ErrorOr<std::unique_ptr<MemoryBuffer>>
181 RealFile::getBuffer(
const Twine &
Name, int64_t FileSize,
182 bool RequiresNullTerminator,
bool IsVolatile) {
183 assert(FD != -1 &&
"cannot get buffer for closed file");
184 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
188 std::error_code RealFile::close() {
189 std::error_code EC = sys::Process::SafelyCloseFileDescriptor(FD);
198 ErrorOr<Status> status(
const Twine &Path)
override;
199 ErrorOr<std::unique_ptr<File>> openFileForRead(
const Twine &Path)
override;
202 llvm::ErrorOr<std::string> getCurrentWorkingDirectory()
const override;
203 std::error_code setCurrentWorkingDirectory(
const Twine &Path)
override;
207 ErrorOr<Status> RealFileSystem::status(
const Twine &Path) {
208 sys::fs::file_status RealStatus;
209 if (std::error_code EC = sys::fs::status(Path, RealStatus))
214 ErrorOr<std::unique_ptr<File>>
215 RealFileSystem::openFileForRead(
const Twine &
Name) {
218 if (std::error_code EC = sys::fs::openFileForRead(Name, FD, &RealName))
220 return std::unique_ptr<File>(
new RealFile(FD, Name.str(), RealName.str()));
223 llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory()
const {
225 if (std::error_code EC = llvm::sys::fs::current_path(Dir))
227 return Dir.str().str();
230 std::error_code RealFileSystem::setCurrentWorkingDirectory(
const Twine &Path) {
239 StringRef Dir = Path.toNullTerminatedStringRef(Storage);
240 if (
int Err = ::chdir(Dir.data()))
241 return std::error_code(Err, std::generic_category());
242 return std::error_code();
253 llvm::sys::fs::directory_iterator Iter;
255 RealFSDirIter(
const Twine &_Path, std::error_code &EC)
256 : Path(_Path.str()), Iter(Path, EC) {
257 if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
258 llvm::sys::fs::file_status
S;
259 EC = Iter->status(S);
265 std::error_code increment()
override {
270 }
else if (Iter == llvm::sys::fs::directory_iterator()) {
273 llvm::sys::fs::file_status
S;
274 EC = Iter->status(S);
283 std::error_code &EC) {
291 FSList.push_back(std::move(BaseFS));
295 FSList.push_back(FS);
304 ErrorOr<Status>
Status = (*I)->status(Path);
305 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
311 ErrorOr<std::unique_ptr<File>>
315 auto Result = (*I)->openFileForRead(Path);
316 if (
Result ||
Result.getError() != llvm::errc::no_such_file_or_directory)
322 llvm::ErrorOr<std::string>
325 return FSList.front()->getCurrentWorkingDirectory();
329 for (
auto &FS : FSList)
330 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
332 return std::error_code();
343 llvm::StringSet<> SeenNames;
345 std::error_code incrementFS() {
346 assert(CurrentFS != Overlays.overlays_end() &&
"incrementing past end");
348 for (
auto E = Overlays.overlays_end(); CurrentFS !=
E; ++CurrentFS) {
350 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
351 if (EC && EC != errc::no_such_file_or_directory)
356 return std::error_code();
359 std::error_code incrementDirIter(
bool IsFirstTime) {
361 "incrementing past end");
364 CurrentDirIter.increment(EC);
370 std::error_code incrementImpl(
bool IsFirstTime) {
372 std::error_code EC = incrementDirIter(IsFirstTime);
377 CurrentEntry = *CurrentDirIter;
378 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
379 if (SeenNames.insert(Name).second)
382 llvm_unreachable(
"returned above");
388 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
389 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
390 EC = incrementImpl(
true);
393 std::error_code increment()
override {
return incrementImpl(
false); }
398 std::error_code &EC) {
400 std::make_shared<OverlayFSDirIterImpl>(Dir, *
this, EC));
417 : Stat(std::move(Stat)), Kind(Kind) {}
425 class InMemoryFile :
public InMemoryNode {
426 std::unique_ptr<llvm::MemoryBuffer>
Buffer;
429 InMemoryFile(
Status Stat, std::unique_ptr<llvm::MemoryBuffer>
Buffer)
430 : InMemoryNode(std::move(Stat),
IME_File), Buffer(std::move(Buffer)) {}
432 llvm::MemoryBuffer *getBuffer() {
return Buffer.get(); }
434 return (std::string(Indent,
' ') + getStatus().getName() +
"\n").str();
436 static bool classof(
const InMemoryNode *N) {
442 class InMemoryFileAdaptor :
public File {
446 explicit InMemoryFileAdaptor(InMemoryFile &
Node) : Node(Node) {}
448 llvm::ErrorOr<Status> status()
override {
return Node.getStatus(); }
449 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
450 getBuffer(
const Twine &Name, int64_t FileSize,
bool RequiresNullTerminator,
451 bool IsVolatile)
override {
452 llvm::MemoryBuffer *Buf =
Node.getBuffer();
453 return llvm::MemoryBuffer::getMemBuffer(
454 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
456 std::error_code close()
override {
return std::error_code(); }
461 std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
467 auto I = Entries.find(Name);
468 if (
I != Entries.end())
469 return I->second.get();
473 return Entries.insert(make_pair(Name, std::move(Child)))
474 .first->second.get();
477 typedef decltype(Entries)::const_iterator const_iterator;
478 const_iterator
begin()
const {
return Entries.begin(); }
479 const_iterator
end()
const {
return Entries.end(); }
481 std::string
toString(
unsigned Indent)
const override {
483 (std::string(Indent,
' ') + getStatus().getName() +
"\n").str();
484 for (
const auto &Entry : Entries) {
485 Result += Entry.second->toString(Indent + 2);
496 : Root(new detail::InMemoryDirectory(
498 0, 0, 0, llvm::sys::fs::file_type::directory_file,
499 llvm::sys::fs::perms::all_all))),
500 UseNormalizedPaths(UseNormalizedPaths) {}
505 return Root->toString(0);
509 std::unique_ptr<llvm::MemoryBuffer>
Buffer) {
519 llvm::sys::path::remove_dots(Path,
true);
535 llvm::sys::TimeValue(ModificationTime, 0), 0, 0,
536 Buffer->getBufferSize(),
537 llvm::sys::fs::file_type::regular_file,
538 llvm::sys::fs::all_all);
539 Dir->
addChild(Name, llvm::make_unique<detail::InMemoryFile>(
540 std::move(Stat), std::move(Buffer)));
547 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
549 0, 0, Buffer->getBufferSize(),
550 llvm::sys::fs::file_type::directory_file, llvm::sys::fs::all_all);
551 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
552 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
556 if (
auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
559 assert(isa<detail::InMemoryFile>(Node) &&
560 "Must be either file or directory!");
567 return cast<detail::InMemoryFile>(
Node)->getBuffer()->getBuffer() ==
574 llvm::MemoryBuffer *
Buffer) {
575 return addFile(P, ModificationTime,
576 llvm::MemoryBuffer::getMemBuffer(
577 Buffer->getBuffer(), Buffer->getBufferIdentifier()));
580 static ErrorOr<detail::InMemoryNode *>
592 llvm::sys::path::remove_dots(Path,
true);
602 return errc::no_such_file_or_directory;
605 if (
auto File = dyn_cast<detail::InMemoryFile>(Node)) {
608 return errc::no_such_file_or_directory;
612 Dir = cast<detail::InMemoryDirectory>(
Node);
621 return (*Node)->getStatus();
622 return Node.getError();
625 llvm::ErrorOr<std::unique_ptr<File>>
629 return Node.getError();
633 if (
auto *F = dyn_cast<detail::InMemoryFile>(*
Node))
634 return std::unique_ptr<File>(
new detail::InMemoryFileAdaptor(*F));
647 InMemoryDirIterator() {}
651 CurrentEntry =
I->second->getStatus();
654 std::error_code increment()
override {
658 CurrentEntry =
I !=
E ?
I->second->getStatus() :
Status();
659 return std::error_code();
665 std::error_code &EC) {
668 EC =
Node.getError();
672 if (
auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*
Node))
689 llvm::sys::path::remove_dots(Path,
true);
692 WorkingDirectory = Path.str();
693 return std::error_code();
717 StringRef getName()
const {
return Name; }
721 class RedirectingDirectoryEntry :
public Entry {
722 std::vector<std::unique_ptr<Entry>> Contents;
726 RedirectingDirectoryEntry(StringRef Name,
727 std::vector<std::unique_ptr<Entry>> Contents,
729 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
731 RedirectingDirectoryEntry(StringRef Name,
Status S)
732 : Entry(EK_Directory, Name), S(std::move(S)) {}
733 Status getStatus() {
return S; }
734 void addContent(std::unique_ptr<Entry> Content) {
735 Contents.push_back(std::move(Content));
737 Entry *getLastContent()
const {
return Contents.back().get(); }
739 iterator contents_begin() {
return Contents.begin(); }
740 iterator contents_end() {
return Contents.end(); }
741 static bool classof(
const Entry *
E) {
return E->getKind() == EK_Directory; }
744 class RedirectingFileEntry :
public Entry {
752 std::string ExternalContentsPath;
755 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
757 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
759 StringRef getExternalContentsPath()
const {
return ExternalContentsPath; }
761 bool useExternalName(
bool GlobalUseExternalName)
const {
762 return UseName == NK_NotSet ? GlobalUseExternalName
763 : (UseName == NK_External);
765 NameKind getUseName()
const {
return UseName; }
766 static bool classof(
const Entry *
E) {
return E->getKind() == EK_File; }
769 class RedirectingFileSystem;
773 RedirectingFileSystem &FS;
777 VFSFromYamlDirIterImpl(
const Twine &Path, RedirectingFileSystem &FS,
780 std::error_code &EC);
840 std::vector<std::unique_ptr<Entry>> Roots;
846 std::string ExternalContentsPrefixDir;
854 bool CaseSensitive =
true;
858 bool IsRelativeOverlay =
false;
862 bool UseExternalNames =
true;
868 bool UseCanonicalizedPaths =
875 friend class RedirectingFileSystemParser;
879 : ExternalFS(std::move(ExternalFS)) {}
882 ErrorOr<Entry *> lookupPath(
const Twine &Path);
886 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
887 sys::path::const_iterator
End, Entry *From);
890 ErrorOr<Status>
status(
const Twine &Path, Entry *
E);
895 static RedirectingFileSystem *
897 SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
900 ErrorOr<Status>
status(
const Twine &Path)
override;
901 ErrorOr<std::unique_ptr<File>>
openFileForRead(
const Twine &Path)
override;
904 return ExternalFS->getCurrentWorkingDirectory();
907 return ExternalFS->setCurrentWorkingDirectory(Path);
911 ErrorOr<Entry *>
E = lookupPath(Dir);
916 ErrorOr<Status> S =
status(Dir, *E);
921 if (!S->isDirectory()) {
922 EC = std::error_code(static_cast<int>(errc::not_a_directory),
923 std::system_category());
927 auto *D = cast<RedirectingDirectoryEntry>(*E);
929 *
this, D->contents_begin(), D->contents_end(), EC));
932 void setExternalContentsPrefixDir(StringRef PrefixDir) {
933 ExternalContentsPrefixDir = PrefixDir.str();
936 StringRef getExternalContentsPrefixDir()
const {
937 return ExternalContentsPrefixDir;
940 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
941 LLVM_DUMP_METHOD
void dump()
const {
942 for (
const std::unique_ptr<Entry> &Root : Roots)
943 dumpEntry(Root.get());
946 LLVM_DUMP_METHOD
void dumpEntry(Entry *E,
int NumSpaces = 0)
const {
947 StringRef Name = E->getName();
948 for (
int i = 0, e = NumSpaces; i < e; ++i)
950 dbgs() <<
"'" << Name.str().c_str() <<
"'" <<
"\n";
952 if (E->getKind() == EK_Directory) {
953 auto *DE = dyn_cast<RedirectingDirectoryEntry>(
E);
954 assert(DE &&
"Should be a directory");
956 for (std::unique_ptr<Entry> &SubEntry :
957 llvm::make_range(DE->contents_begin(), DE->contents_end()))
958 dumpEntry(SubEntry.get(), NumSpaces+2);
966 class RedirectingFileSystemParser {
967 yaml::Stream &Stream;
970 Stream.printError(N, Msg);
974 bool parseScalarString(
yaml::Node *N, StringRef &Result,
976 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
978 error(N,
"expected string");
981 Result = S->getValue(Storage);
986 bool parseScalarBool(
yaml::Node *N,
bool &Result) {
989 if (!parseScalarString(N, Value, Storage))
992 if (Value.equals_lower(
"true") || Value.equals_lower(
"on") ||
993 Value.equals_lower(
"yes") || Value ==
"1") {
996 }
else if (Value.equals_lower(
"false") || Value.equals_lower(
"off") ||
997 Value.equals_lower(
"no") || Value ==
"0") {
1002 error(N,
"expected boolean value");
1007 KeyStatus(
bool Required=
false) : Required(Required), Seen(
false) {}
1011 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
1014 bool checkDuplicateOrUnknownKey(
yaml::Node *KeyNode, StringRef Key,
1015 DenseMap<StringRef, KeyStatus> &Keys) {
1016 if (!Keys.count(Key)) {
1017 error(KeyNode,
"unknown key");
1020 KeyStatus &S = Keys[Key];
1022 error(KeyNode, Twine(
"duplicate key '") + Key +
"'");
1030 bool checkMissingKeys(
yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
1034 if (
I->second.Required && !
I->second.Seen) {
1035 error(Obj, Twine(
"missing key '") +
I->first +
"'");
1042 Entry *lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1043 Entry *ParentEntry =
nullptr) {
1045 for (
const std::unique_ptr<Entry> &Root : FS->Roots) {
1046 if (Name.equals(Root->getName())) {
1047 ParentEntry = Root.get();
1052 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1053 for (std::unique_ptr<Entry> &Content :
1054 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1055 auto *DirContent = dyn_cast<RedirectingDirectoryEntry>(Content.get());
1056 if (DirContent && Name.equals(Content->getName()))
1062 std::unique_ptr<Entry> E = llvm::make_unique<RedirectingDirectoryEntry>(
1064 0, file_type::directory_file, sys::fs::all_all));
1067 FS->Roots.push_back(std::move(E));
1068 ParentEntry = FS->Roots.back().get();
1072 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1073 DE->addContent(std::move(E));
1074 return DE->getLastContent();
1077 void uniqueOverlayTree(RedirectingFileSystem *FS, Entry *SrcE,
1078 Entry *NewParentE =
nullptr) {
1079 StringRef Name = SrcE->getName();
1080 switch (SrcE->getKind()) {
1081 case EK_Directory: {
1082 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1083 assert(DE &&
"Must be a directory");
1088 NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1089 for (std::unique_ptr<Entry> &SubEntry :
1090 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1091 uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1095 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1096 assert(FE &&
"Must be a file");
1097 assert(NewParentE &&
"Parent entry must exist");
1098 auto *DE = dyn_cast<RedirectingDirectoryEntry>(NewParentE);
1099 DE->addContent(llvm::make_unique<RedirectingFileEntry>(
1100 Name, FE->getExternalContentsPath(), FE->getUseName()));
1106 std::unique_ptr<Entry> parseEntry(
yaml::Node *N, RedirectingFileSystem *FS) {
1107 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
1109 error(N,
"expected mapping node for file or directory entry");
1113 KeyStatusPair Fields[] = {
1114 KeyStatusPair(
"name",
true),
1115 KeyStatusPair(
"type",
true),
1116 KeyStatusPair(
"contents",
false),
1117 KeyStatusPair(
"external-contents",
false),
1118 KeyStatusPair(
"use-external-name",
false),
1123 bool HasContents =
false;
1124 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
1125 std::string ExternalContentsPath;
1127 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
1136 if (!parseScalarString(
I->getKey(), Key,
Buffer))
1139 if (!checkDuplicateOrUnknownKey(
I->getKey(), Key, Keys))
1143 if (Key ==
"name") {
1147 if (FS->UseCanonicalizedPaths) {
1151 Path = sys::path::remove_leading_dotslash(Path);
1152 sys::path::remove_dots(Path,
true);
1157 }
else if (Key ==
"type") {
1160 if (Value ==
"file")
1162 else if (Value ==
"directory")
1163 Kind = EK_Directory;
1165 error(
I->getValue(),
"unknown value for 'type'");
1168 }
else if (Key ==
"contents") {
1171 "entry already has 'contents' or 'external-contents'");
1175 yaml::SequenceNode *Contents =
1176 dyn_cast<yaml::SequenceNode>(
I->getValue());
1179 error(
I->getValue(),
"expected array");
1184 E = Contents->end();
1186 if (std::unique_ptr<Entry> E = parseEntry(&*
I, FS))
1187 EntryArrayContents.push_back(std::move(E));
1191 }
else if (Key ==
"external-contents") {
1194 "entry already has 'contents' or 'external-contents'");
1202 if (FS->IsRelativeOverlay) {
1203 FullPath = FS->getExternalContentsPrefixDir();
1204 assert(!FullPath.empty() &&
1205 "External contents prefix directory must exist");
1206 llvm::sys::path::append(FullPath, Value);
1211 if (FS->UseCanonicalizedPaths) {
1214 FullPath = sys::path::remove_leading_dotslash(FullPath);
1215 sys::path::remove_dots(FullPath,
true);
1217 ExternalContentsPath = FullPath.str();
1218 }
else if (Key ==
"use-external-name") {
1220 if (!parseScalarBool(
I->getValue(), Val))
1222 UseExternalName = Val ? RedirectingFileEntry::NK_External
1223 : RedirectingFileEntry::NK_Virtual;
1225 llvm_unreachable(
"key missing from Keys");
1229 if (Stream.failed())
1234 error(N,
"missing key 'contents' or 'external-contents'");
1237 if (!checkMissingKeys(N, Keys))
1241 if (Kind == EK_Directory &&
1242 UseExternalName != RedirectingFileEntry::NK_NotSet) {
1243 error(N,
"'use-external-name' is not supported for directories");
1248 StringRef Trimmed(Name);
1249 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1250 while (Trimmed.size() > RootPathLen &&
1251 sys::path::is_separator(Trimmed.back()))
1252 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1254 StringRef LastComponent = sys::path::filename(Trimmed);
1256 std::unique_ptr<Entry> Result;
1259 Result = llvm::make_unique<RedirectingFileEntry>(
1260 LastComponent, std::move(ExternalContentsPath), UseExternalName);
1263 Result = llvm::make_unique<RedirectingDirectoryEntry>(
1264 LastComponent, std::move(EntryArrayContents),
1266 file_type::directory_file, sys::fs::all_all));
1270 StringRef Parent = sys::path::parent_path(Trimmed);
1275 for (sys::path::reverse_iterator
I = sys::path::rbegin(Parent),
1276 E = sys::path::rend(Parent);
1278 std::vector<std::unique_ptr<Entry>> Entries;
1279 Entries.push_back(std::move(Result));
1280 Result = llvm::make_unique<RedirectingDirectoryEntry>(
1281 *
I, std::move(Entries),
1283 file_type::directory_file, sys::fs::all_all));
1289 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
1292 bool parse(
yaml::Node *Root, RedirectingFileSystem *FS) {
1293 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
1295 error(Root,
"expected mapping node");
1299 KeyStatusPair Fields[] = {
1300 KeyStatusPair(
"version",
true),
1301 KeyStatusPair(
"case-sensitive",
false),
1302 KeyStatusPair(
"use-external-names",
false),
1303 KeyStatusPair(
"overlay-relative",
false),
1304 KeyStatusPair(
"roots",
true),
1308 std::vector<std::unique_ptr<Entry>> RootEntries;
1315 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
1318 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
1321 if (Key ==
"roots") {
1322 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
1324 error(I->getValue(),
"expected array");
1330 if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
1331 RootEntries.push_back(std::move(E));
1335 }
else if (Key ==
"version") {
1336 StringRef VersionString;
1338 if (!parseScalarString(I->getValue(), VersionString, Storage))
1341 if (VersionString.getAsInteger<
int>(10, Version)) {
1342 error(I->getValue(),
"expected integer");
1346 error(I->getValue(),
"invalid version number");
1350 error(I->getValue(),
"version mismatch, expected 0");
1353 }
else if (Key ==
"case-sensitive") {
1354 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
1356 }
else if (Key ==
"overlay-relative") {
1357 if (!parseScalarBool(I->getValue(), FS->IsRelativeOverlay))
1359 }
else if (Key ==
"use-external-names") {
1360 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
1363 llvm_unreachable(
"key missing from Keys");
1367 if (Stream.failed())
1370 if (!checkMissingKeys(Top, Keys))
1376 for (std::unique_ptr<Entry> &E : RootEntries)
1377 uniqueOverlayTree(FS, E.get());
1384 Entry::~Entry() =
default;
1386 RedirectingFileSystem *
1388 SourceMgr::DiagHandlerTy DiagHandler,
1389 StringRef YAMLFilePath,
void *DiagContext,
1393 yaml::Stream Stream(Buffer->getMemBufferRef(),
SM);
1395 SM.setDiagHandler(DiagHandler, DiagContext);
1396 yaml::document_iterator DI = Stream.begin();
1398 if (DI == Stream.end() || !Root) {
1399 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error,
"expected root node");
1403 RedirectingFileSystemParser
P(Stream);
1405 std::unique_ptr<RedirectingFileSystem> FS(
1406 new RedirectingFileSystem(std::move(ExternalFS)));
1408 if (!YAMLFilePath.empty()) {
1418 std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1419 assert(!EC &&
"Overlay dir final path must be absolute");
1421 FS->setExternalContentsPrefixDir(OverlayAbsDir);
1424 if (!
P.parse(Root, FS.get()))
1427 return FS.release();
1430 ErrorOr<Entry *> RedirectingFileSystem::lookupPath(
const Twine &Path_) {
1432 Path_.toVector(Path);
1435 if (std::error_code EC = makeAbsolute(Path))
1441 if (UseCanonicalizedPaths) {
1442 Path = sys::path::remove_leading_dotslash(Path);
1443 sys::path::remove_dots(Path,
true);
1451 for (
const std::unique_ptr<Entry> &Root : Roots) {
1452 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
1453 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
1460 RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1461 sys::path::const_iterator End, Entry *From) {
1462 #ifndef LLVM_ON_WIN32
1465 "Paths should not contain traversal components");
1469 if (Start->equals(
"."))
1473 StringRef FromName = From->getName();
1476 if (!FromName.empty()) {
1477 if (CaseSensitive ? !Start->equals(FromName)
1478 : !Start->equals_lower(FromName))
1490 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
1494 for (
const std::unique_ptr<Entry> &DirEntry :
1495 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1496 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
1497 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
1505 Status S = ExternalStatus;
1506 if (!UseExternalNames)
1507 S = Status::copyWithNewName(S, Path.str());
1512 ErrorOr<Status> RedirectingFileSystem::status(
const Twine &Path, Entry *E) {
1513 assert(E !=
nullptr);
1514 if (
auto *F = dyn_cast<RedirectingFileEntry>(E)) {
1515 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
1516 assert(!S || S->getName() == F->getExternalContentsPath());
1522 auto *DE = cast<RedirectingDirectoryEntry>(
E);
1523 return Status::copyWithNewName(DE->getStatus(), Path.str());
1527 ErrorOr<Status> RedirectingFileSystem::status(
const Twine &Path) {
1528 ErrorOr<Entry *> Result = lookupPath(Path);
1530 return Result.getError();
1531 return status(Path, *Result);
1536 class FileWithFixedStatus :
public File {
1537 std::unique_ptr<File> InnerFile;
1541 FileWithFixedStatus(std::unique_ptr<File> InnerFile,
Status S)
1542 : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
1544 ErrorOr<Status>
status()
override {
return S; }
1545 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
1546 getBuffer(
const Twine &Name, int64_t FileSize,
bool RequiresNullTerminator,
1547 bool IsVolatile)
override {
1548 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1551 std::error_code
close()
override {
return InnerFile->close(); }
1555 ErrorOr<std::unique_ptr<File>>
1556 RedirectingFileSystem::openFileForRead(
const Twine &Path) {
1557 ErrorOr<Entry *> E = lookupPath(Path);
1559 return E.getError();
1561 auto *F = dyn_cast<RedirectingFileEntry>(*E);
1565 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1569 auto ExternalStatus = (*Result)->status();
1570 if (!ExternalStatus)
1571 return ExternalStatus.getError();
1576 return std::unique_ptr<File>(
1577 llvm::make_unique<FileWithFixedStatus>(std::move(*Result),
S));
1582 SourceMgr::DiagHandlerTy DiagHandler,
1583 StringRef YAMLFilePath,
1587 YAMLFilePath, DiagContext,
1588 std::move(ExternalFS));
1592 static std::atomic<unsigned> UID;
1593 unsigned ID = ++UID;
1599 void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1600 assert(sys::path::is_absolute(VirtualPath) &&
"virtual path not absolute");
1601 assert(sys::path::is_absolute(RealPath) &&
"real path not absolute");
1602 assert(!
pathHasTraversal(VirtualPath) &&
"path traversal is not supported");
1603 Mappings.emplace_back(VirtualPath, RealPath);
1608 llvm::raw_ostream &OS;
1610 inline unsigned getDirIndent() {
return 4 * DirStack.size(); }
1611 inline unsigned getFileIndent() {
return 4 * (DirStack.size() + 1); }
1612 bool containedIn(StringRef Parent, StringRef Path);
1613 StringRef containedPart(StringRef Parent, StringRef Path);
1614 void startDirectory(StringRef Path);
1615 void endDirectory();
1616 void writeEntry(StringRef VPath, StringRef RPath);
1619 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
1622 StringRef OverlayDir);
1626 bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
1627 using namespace llvm::sys;
1631 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1632 if (*IParent != *IChild)
1636 return IParent == EParent;
1639 StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1640 assert(!Parent.empty());
1641 assert(containedIn(Parent, Path));
1642 return Path.slice(Parent.size() + 1, StringRef::npos);
1645 void JSONWriter::startDirectory(StringRef Path) {
1647 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1648 DirStack.push_back(Path);
1649 unsigned Indent = getDirIndent();
1650 OS.indent(Indent) <<
"{\n";
1651 OS.indent(Indent + 2) <<
"'type': 'directory',\n";
1652 OS.indent(Indent + 2) <<
"'name': \"" << llvm::yaml::escape(Name) <<
"\",\n";
1653 OS.indent(Indent + 2) <<
"'contents': [\n";
1656 void JSONWriter::endDirectory() {
1657 unsigned Indent = getDirIndent();
1658 OS.indent(Indent + 2) <<
"]\n";
1659 OS.indent(Indent) <<
"}";
1661 DirStack.pop_back();
1664 void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1665 unsigned Indent = getFileIndent();
1666 OS.indent(Indent) <<
"{\n";
1667 OS.indent(Indent + 2) <<
"'type': 'file',\n";
1668 OS.indent(Indent + 2) <<
"'name': \"" << llvm::yaml::escape(VPath) <<
"\",\n";
1669 OS.indent(Indent + 2) <<
"'external-contents': \""
1670 << llvm::yaml::escape(RPath) <<
"\"\n";
1671 OS.indent(Indent) <<
"}";
1678 StringRef OverlayDir) {
1679 using namespace llvm::sys;
1683 if (IsCaseSensitive.hasValue())
1684 OS <<
" 'case-sensitive': '"
1685 << (IsCaseSensitive.getValue() ?
"true" :
"false") <<
"',\n";
1686 if (UseExternalNames.hasValue())
1687 OS <<
" 'use-external-names': '"
1688 << (UseExternalNames.getValue() ?
"true" :
"false") <<
"',\n";
1689 bool UseOverlayRelative =
false;
1690 if (IsOverlayRelative.hasValue()) {
1691 UseOverlayRelative = IsOverlayRelative.getValue();
1692 OS <<
" 'overlay-relative': '"
1693 << (UseOverlayRelative ?
"true" :
"false") <<
"',\n";
1695 OS <<
" 'roots': [\n";
1697 if (!Entries.empty()) {
1699 startDirectory(path::parent_path(Entry.
VPath));
1701 StringRef RPath = Entry.
RPath;
1702 if (UseOverlayRelative) {
1703 unsigned OverlayDirLen = OverlayDir.size();
1704 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1705 "Overlay dir must be contained in RPath");
1706 RPath = RPath.slice(OverlayDirLen, RPath.size());
1709 writeEntry(path::filename(Entry.
VPath), RPath);
1711 for (
const auto &Entry : Entries.slice(1)) {
1712 StringRef Dir = path::parent_path(Entry.
VPath);
1713 if (Dir == DirStack.back())
1716 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1721 startDirectory(Dir);
1723 StringRef RPath = Entry.
RPath;
1724 if (UseOverlayRelative) {
1725 unsigned OverlayDirLen = OverlayDir.size();
1726 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1727 "Overlay dir must be contained in RPath");
1728 RPath = RPath.slice(OverlayDirLen, RPath.size());
1730 writeEntry(path::filename(Entry.
VPath), RPath);
1733 while (!DirStack.empty()) {
1745 std::sort(Mappings.begin(), Mappings.end(),
1747 return LHS.
VPath < RHS.VPath;
1750 JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
1751 IsOverlayRelative, OverlayDir);
1754 VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1755 const Twine &_Path, RedirectingFileSystem &FS,
1758 : Dir(_Path.str()), FS(FS),
Current(Begin), End(End) {
1761 llvm::sys::path::append(PathStr, (*Current)->getName());
1762 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
1770 std::error_code VFSFromYamlDirIterImpl::increment() {
1771 assert(
Current != End &&
"cannot iterate past end");
1774 llvm::sys::path::append(PathStr, (*Current)->getName());
1775 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
1777 return S.getError();
1782 return std::error_code();
1787 std::error_code &EC)
1791 State = std::make_shared<IterState>();
1798 assert(FS && State && !State->empty() &&
"incrementing past end");
1799 assert(State->top()->isStatusKnown() &&
"non-canonical end iterator");
1801 if (State->top()->isDirectory()) {
1811 while (!State->empty() && State->top().increment(EC) ==
End)
static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames, Status ExternalStatus)
decltype(Entries) typedef::const_iterator const_iterator
const_iterator begin() const
static bool classof(const InMemoryNode *N)
Defines the clang::FileManager interface and associated types.
bool addFile(const Twine &Path, time_t ModificationTime, std::unique_ptr< llvm::MemoryBuffer > Buffer)
Add a buffer to the VFS with a path.
IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
virtual llvm::ErrorOr< Status > status()=0
Get the status of the file.
The base class of the type hierarchy.
bool equivalent(const Status &Other) const
std::unique_ptr< llvm::MemoryBuffer > Buffer
bool isStatusKnown() const
llvm::sys::TimeValue getLastModificationTime() const
InMemoryNode * getChild(StringRef Name)
virtual llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBuffer(const Twine &Name, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)=0
Get the contents of the file as a MemoryBuffer.
virtual llvm::ErrorOr< std::unique_ptr< File > > openFileForRead(const Twine &Path)=0
Get a File object for the file at Path, if one exists.
virtual directory_iterator dir_begin(const Twine &Dir, std::error_code &EC)=0
Get a directory_iterator for Dir.
bool useNormalizedPaths() const
Return true if this file system normalizes . and .. in paths.
The virtual file system interface.
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
void write(llvm::raw_ostream &OS)
virtual std::error_code close()=0
Closes the file.
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.
An input iterator over the recursive contents of a virtual path, similar to llvm::sys::fs::recursive_...
An in-memory file system.
directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override
Get a directory_iterator for Dir.
bool addFileNoOwn(const Twine &Path, time_t ModificationTime, llvm::MemoryBuffer *Buffer)
Add a buffer to the VFS with a path.
directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override
Get a directory_iterator for Dir.
A file system that allows overlaying one AbstractFileSystem on top of another.
virtual llvm::ErrorOr< Status > status(const Twine &Path)=0
Get the status of the entry at Path, if one exists.
InMemoryDirectory(Status Stat)
llvm::sys::fs::file_type getType() const
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
InMemoryNode(Status Stat, InMemoryNodeKind Kind)
FileSystemList::reverse_iterator iterator
llvm::ErrorOr< std::unique_ptr< File > > openFileForRead(const Twine &Path) override
Get a File object for the file at Path, if one exists.
The result of a status operation.
void pushOverlay(IntrusiveRefCntPtr< FileSystem > FS)
Pushes a file system on top of the stack.
detail::InMemoryDirectory::const_iterator I
recursive_directory_iterator()
Construct an 'end' iterator.
virtual std::error_code setCurrentWorkingDirectory(const Twine &Path)=0
Set the working directory.
The in memory file system is a tree of Nodes.
llvm::sys::fs::UniqueID getUniqueID() const
virtual llvm::ErrorOr< std::string > getCurrentWorkingDirectory() const =0
Get the working directory of this file system.
static Status copyWithNewName(const Status &In, StringRef NewName)
Get a copy of a Status with a different name.
iterator overlays_end()
Get an iterator pointing one-past the least recently added file system.
llvm::ErrorOr< std::string > getCurrentWorkingDirectory() const override
Get the working directory of this file system.
static bool pathHasTraversal(StringRef Path)
static bool isTraversalComponent(StringRef Component)
The result type of a method or function.
~InMemoryFileSystem() override
InMemoryNodeKind getKind() const
InMemoryFileSystem(bool UseNormalizedPaths=true)
recursive_directory_iterator & increment(std::error_code &EC)
Equivalent to operator++, with an error code.
std::string toString() const
const TemplateArgument * iterator
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
iterator overlays_begin()
Get an iterator pointing to the most recently added file system.
const_iterator end() const
InMemoryNode * addChild(StringRef Name, std::unique_ptr< InMemoryNode > Child)
std::error_code setCurrentWorkingDirectory(const Twine &Path) override
Set the working directory.
Represents a template argument.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
bool isRegularFile() const
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
Defines the virtual file system interface vfs::FileSystem.
const Status & getStatus() const
llvm::sys::fs::perms getPermissions() const
detail::InMemoryDirectory::const_iterator E
OverlayFileSystem(IntrusiveRefCntPtr< FileSystem > Base)
llvm::sys::fs::UniqueID getNextVirtualUniqueID()
Get a globally unique ID for a virtual file or directory.
static ErrorOr< detail::InMemoryNode * > lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir, const Twine &P)
bool exists(const Twine &Path)
Check whether a file exists. Provided for convenience.
std::string toString(const til::SExpr *E)
static bool classof(const OMPClause *T)
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...
std::string toString(unsigned Indent) const override
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
virtual ~File()
Destroy the file after closing it (if open).
An input iterator over the entries in a virtual path, similar to llvm::sys::fs::directory_iterator.
llvm::ErrorOr< Status > status(const Twine &Path) override
Get the status of the entry at Path, if one exists.
std::error_code setCurrentWorkingDirectory(const Twine &Path) override
Set the working directory.
static Decl::Kind getKind(const Decl *D)
An interface for virtual file systems to provide an iterator over the (non-recursive) contents of a d...
llvm::ErrorOr< Status > status(const Twine &Path) override
Get the status of the entry at Path, if one exists.
virtual std::error_code increment()=0
Sets CurrentEntry to the next entry in the directory on success, or returns a system-defined error_co...
std::error_code makeAbsolute(SmallVectorImpl< char > &Path) const
Make Path an absolute path.