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/Support/Errc.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/YAMLParser.h"
23 #include "llvm/Config/llvm-config.h"
34 using namespace clang;
35 using namespace clang::vfs;
37 using llvm::sys::fs::file_status;
38 using llvm::sys::fs::file_type;
39 using llvm::sys::fs::perms;
40 using llvm::sys::fs::UniqueID;
43 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
44 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
45 Type(Status.
type()), Perms(Status.permissions()), IsVFSMapped(
false) {}
47 Status::Status(StringRef
Name, UniqueID UID, sys::TimeValue MTime,
48 uint32_t User, uint32_t Group, uint64_t Size, file_type
Type,
50 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
51 Type(Type), Perms(Perms), IsVFSMapped(
false) {}
53 Status Status::copyWithNewName(
const Status &In, StringRef NewName) {
60 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
61 In.getUser(), In.getGroup(), In.getSize(), In.type(),
69 return Type == file_type::directory_file;
72 return Type == file_type::regular_file;
78 return Type == file_type::symlink_file;
81 return Type != file_type::status_error;
91 ErrorOr<std::unique_ptr<MemoryBuffer>>
93 bool RequiresNullTerminator,
bool IsVolatile) {
98 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
104 return WorkingDir.getError();
106 return llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
120 class RealFile :
public File {
123 friend class RealFileSystem;
124 RealFile(
int FD, StringRef NewName)
125 : FD(FD),
S(NewName, {}, {}, {}, {}, {},
126 llvm::sys::fs::file_type::status_error, {}) {
127 assert(FD >= 0 &&
"Invalid or inactive file descriptor");
131 ~RealFile()
override;
132 ErrorOr<Status> status()
override;
133 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(
const Twine &
Name,
135 bool RequiresNullTerminator,
136 bool IsVolatile)
override;
137 std::error_code close()
override;
140 RealFile::~RealFile() { close(); }
142 ErrorOr<Status> RealFile::status() {
143 assert(FD != -1 &&
"cannot stat closed file");
144 if (!
S.isStatusKnown()) {
145 file_status RealStatus;
146 if (std::error_code EC = sys::fs::status(FD, RealStatus))
153 ErrorOr<std::unique_ptr<MemoryBuffer>>
154 RealFile::getBuffer(
const Twine &
Name, int64_t FileSize,
155 bool RequiresNullTerminator,
bool IsVolatile) {
156 assert(FD != -1 &&
"cannot get buffer for closed file");
157 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
162 #if !defined(_MSC_VER) && !defined(__MINGW32__)
168 #define S_ISFIFO(x) (0)
171 std::error_code RealFile::close() {
173 return std::error_code(errno, std::generic_category());
175 return std::error_code();
182 ErrorOr<Status> status(
const Twine &Path)
override;
183 ErrorOr<std::unique_ptr<File>> openFileForRead(
const Twine &Path)
override;
186 llvm::ErrorOr<std::string> getCurrentWorkingDirectory()
const override;
187 std::error_code setCurrentWorkingDirectory(
const Twine &Path)
override;
191 ErrorOr<Status> RealFileSystem::status(
const Twine &Path) {
192 sys::fs::file_status RealStatus;
193 if (std::error_code EC = sys::fs::status(Path, RealStatus))
198 ErrorOr<std::unique_ptr<File>>
199 RealFileSystem::openFileForRead(
const Twine &
Name) {
201 if (std::error_code EC = sys::fs::openFileForRead(Name, FD))
203 return std::unique_ptr<File>(
new RealFile(FD, Name.str()));
206 llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory()
const {
208 if (std::error_code EC = llvm::sys::fs::current_path(Dir))
210 return Dir.str().str();
213 std::error_code RealFileSystem::setCurrentWorkingDirectory(
const Twine &Path) {
222 StringRef Dir = Path.toNullTerminatedStringRef(Storage);
223 if (
int Err = ::chdir(Dir.data()))
224 return std::error_code(Err, std::generic_category());
225 return std::error_code();
236 llvm::sys::fs::directory_iterator Iter;
238 RealFSDirIter(
const Twine &_Path, std::error_code &EC)
239 : Path(_Path.str()), Iter(Path, EC) {
240 if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
241 llvm::sys::fs::file_status
S;
242 EC = Iter->status(S);
248 std::error_code increment()
override {
253 }
else if (Iter == llvm::sys::fs::directory_iterator()) {
256 llvm::sys::fs::file_status
S;
257 EC = Iter->status(S);
266 std::error_code &EC) {
274 FSList.push_back(BaseFS);
278 FSList.push_back(FS);
287 ErrorOr<Status>
Status = (*I)->status(Path);
288 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
294 ErrorOr<std::unique_ptr<File>>
298 auto Result = (*I)->openFileForRead(Path);
299 if (
Result ||
Result.getError() != llvm::errc::no_such_file_or_directory)
305 llvm::ErrorOr<std::string>
308 return FSList.front()->getCurrentWorkingDirectory();
312 for (
auto &FS : FSList)
313 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
315 return std::error_code();
326 llvm::StringSet<> SeenNames;
328 std::error_code incrementFS() {
329 assert(CurrentFS != Overlays.overlays_end() &&
"incrementing past end");
331 for (
auto E = Overlays.overlays_end(); CurrentFS !=
E; ++CurrentFS) {
333 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
334 if (EC && EC != errc::no_such_file_or_directory)
339 return std::error_code();
342 std::error_code incrementDirIter(
bool IsFirstTime) {
344 "incrementing past end");
347 CurrentDirIter.increment(EC);
353 std::error_code incrementImpl(
bool IsFirstTime) {
355 std::error_code EC = incrementDirIter(IsFirstTime);
360 CurrentEntry = *CurrentDirIter;
361 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
362 if (SeenNames.insert(Name).second)
365 llvm_unreachable(
"returned above");
371 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
372 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
373 EC = incrementImpl(
true);
376 std::error_code increment()
override {
return incrementImpl(
false); }
381 std::error_code &EC) {
383 std::make_shared<OverlayFSDirIterImpl>(Dir, *
this, EC));
400 : Stat(std::move(Stat)), Kind(Kind) {}
408 class InMemoryFile :
public InMemoryNode {
409 std::unique_ptr<llvm::MemoryBuffer>
Buffer;
412 InMemoryFile(
Status Stat, std::unique_ptr<llvm::MemoryBuffer>
Buffer)
413 : InMemoryNode(std::move(Stat),
IME_File), Buffer(std::move(Buffer)) {}
415 llvm::MemoryBuffer *getBuffer() {
return Buffer.get(); }
417 return (std::string(Indent,
' ') + getStatus().getName() +
"\n").str();
419 static bool classof(
const InMemoryNode *N) {
425 class InMemoryFileAdaptor :
public File {
429 explicit InMemoryFileAdaptor(InMemoryFile &
Node) : Node(Node) {}
431 llvm::ErrorOr<Status> status()
override {
return Node.getStatus(); }
432 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
433 getBuffer(
const Twine &Name, int64_t FileSize,
bool RequiresNullTerminator,
434 bool IsVolatile)
override {
435 llvm::MemoryBuffer *Buf =
Node.getBuffer();
436 return llvm::MemoryBuffer::getMemBuffer(
437 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
439 std::error_code close()
override {
return std::error_code(); }
444 std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
450 auto I = Entries.find(Name);
451 if (
I != Entries.end())
452 return I->second.get();
456 return Entries.insert(make_pair(Name, std::move(Child)))
457 .first->second.get();
460 typedef decltype(Entries)::const_iterator const_iterator;
461 const_iterator
begin()
const {
return Entries.begin(); }
462 const_iterator
end()
const {
return Entries.end(); }
464 std::string
toString(
unsigned Indent)
const override {
466 (std::string(Indent,
' ') + getStatus().getName() +
"\n").str();
467 for (
const auto &Entry : Entries) {
468 Result += Entry.second->toString(Indent + 2);
479 : Root(new detail::InMemoryDirectory(
481 0, 0, 0, llvm::sys::fs::file_type::directory_file,
482 llvm::sys::fs::perms::all_all))),
483 UseNormalizedPaths(UseNormalizedPaths) {}
488 return Root->toString(0);
492 std::unique_ptr<llvm::MemoryBuffer>
Buffer) {
502 llvm::sys::path::remove_dots(Path,
true);
518 llvm::sys::TimeValue(ModificationTime, 0), 0, 0,
519 Buffer->getBufferSize(),
520 llvm::sys::fs::file_type::regular_file,
521 llvm::sys::fs::all_all);
522 Dir->
addChild(Name, llvm::make_unique<detail::InMemoryFile>(
523 std::move(Stat), std::move(Buffer)));
530 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
532 0, 0, Buffer->getBufferSize(),
533 llvm::sys::fs::file_type::directory_file, llvm::sys::fs::all_all);
534 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
535 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
539 if (
auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
542 assert(isa<detail::InMemoryFile>(Node) &&
543 "Must be either file or directory!");
550 return cast<detail::InMemoryFile>(
Node)->getBuffer()->getBuffer() ==
557 llvm::MemoryBuffer *
Buffer) {
558 return addFile(P, ModificationTime,
559 llvm::MemoryBuffer::getMemBuffer(
560 Buffer->getBuffer(), Buffer->getBufferIdentifier()));
563 static ErrorOr<detail::InMemoryNode *>
575 llvm::sys::path::remove_dots(Path,
true);
585 return errc::no_such_file_or_directory;
588 if (
auto File = dyn_cast<detail::InMemoryFile>(Node)) {
591 return errc::no_such_file_or_directory;
595 Dir = cast<detail::InMemoryDirectory>(
Node);
604 return (*Node)->getStatus();
605 return Node.getError();
608 llvm::ErrorOr<std::unique_ptr<File>>
612 return Node.getError();
616 if (
auto *F = dyn_cast<detail::InMemoryFile>(*
Node))
617 return std::unique_ptr<File>(
new detail::InMemoryFileAdaptor(*F));
630 InMemoryDirIterator() {}
634 CurrentEntry =
I->second->getStatus();
637 std::error_code increment()
override {
641 CurrentEntry =
I !=
E ?
I->second->getStatus() :
Status();
642 return std::error_code();
648 std::error_code &EC) {
651 EC =
Node.getError();
655 if (
auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*
Node))
672 llvm::sys::path::remove_dots(Path,
true);
675 WorkingDirectory = Path.str();
676 return std::error_code();
700 StringRef getName()
const {
return Name; }
704 class RedirectingDirectoryEntry :
public Entry {
705 std::vector<std::unique_ptr<Entry>> Contents;
709 RedirectingDirectoryEntry(StringRef Name,
710 std::vector<std::unique_ptr<Entry>> Contents,
712 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
714 Status getStatus() {
return S; }
716 iterator contents_begin() {
return Contents.begin(); }
717 iterator contents_end() {
return Contents.end(); }
718 static bool classof(
const Entry *
E) {
return E->getKind() == EK_Directory; }
721 class RedirectingFileEntry :
public Entry {
729 std::string ExternalContentsPath;
732 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
734 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
736 StringRef getExternalContentsPath()
const {
return ExternalContentsPath; }
738 bool useExternalName(
bool GlobalUseExternalName)
const {
739 return UseName == NK_NotSet ? GlobalUseExternalName
740 : (UseName == NK_External);
742 static bool classof(
const Entry *
E) {
return E->getKind() == EK_File; }
745 class RedirectingFileSystem;
749 RedirectingFileSystem &FS;
753 VFSFromYamlDirIterImpl(
const Twine &Path, RedirectingFileSystem &FS,
756 std::error_code &EC);
815 std::vector<std::unique_ptr<Entry>> Roots;
829 bool UseExternalNames;
832 friend class RedirectingFileSystemParser;
836 : ExternalFS(ExternalFS), CaseSensitive(
true), UseExternalNames(
true) {}
839 ErrorOr<Entry *> lookupPath(
const Twine &Path);
843 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
844 sys::path::const_iterator
End, Entry *From);
847 ErrorOr<Status>
status(
const Twine &Path, Entry *
E);
852 static RedirectingFileSystem *
854 SourceMgr::DiagHandlerTy DiagHandler,
void *DiagContext,
857 ErrorOr<Status>
status(
const Twine &Path)
override;
858 ErrorOr<std::unique_ptr<File>>
openFileForRead(
const Twine &Path)
override;
861 return ExternalFS->getCurrentWorkingDirectory();
864 return ExternalFS->setCurrentWorkingDirectory(Path);
868 ErrorOr<Entry *>
E = lookupPath(Dir);
873 ErrorOr<Status> S =
status(Dir, *E);
878 if (!S->isDirectory()) {
879 EC = std::error_code(static_cast<int>(errc::not_a_directory),
880 std::system_category());
884 auto *D = cast<RedirectingDirectoryEntry>(*E);
886 *
this, D->contents_begin(), D->contents_end(), EC));
891 class RedirectingFileSystemParser {
892 yaml::Stream &Stream;
895 Stream.printError(N, Msg);
899 bool parseScalarString(
yaml::Node *N, StringRef &Result,
901 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
903 error(N,
"expected string");
906 Result = S->getValue(Storage);
911 bool parseScalarBool(
yaml::Node *N,
bool &Result) {
914 if (!parseScalarString(N, Value, Storage))
917 if (Value.equals_lower(
"true") || Value.equals_lower(
"on") ||
918 Value.equals_lower(
"yes") || Value ==
"1") {
921 }
else if (Value.equals_lower(
"false") || Value.equals_lower(
"off") ||
922 Value.equals_lower(
"no") || Value ==
"0") {
927 error(N,
"expected boolean value");
932 KeyStatus(
bool Required=
false) : Required(Required), Seen(
false) {}
936 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
939 bool checkDuplicateOrUnknownKey(
yaml::Node *KeyNode, StringRef Key,
940 DenseMap<StringRef, KeyStatus> &Keys) {
941 if (!Keys.count(Key)) {
942 error(KeyNode,
"unknown key");
945 KeyStatus &S = Keys[Key];
947 error(KeyNode, Twine(
"duplicate key '") + Key +
"'");
955 bool checkMissingKeys(
yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
959 if (
I->second.Required && !
I->second.Seen) {
960 error(Obj, Twine(
"missing key '") +
I->first +
"'");
967 std::unique_ptr<Entry> parseEntry(
yaml::Node *N) {
968 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
970 error(N,
"expected mapping node for file or directory entry");
974 KeyStatusPair Fields[] = {
975 KeyStatusPair(
"name",
true),
976 KeyStatusPair(
"type",
true),
977 KeyStatusPair(
"contents",
false),
978 KeyStatusPair(
"external-contents",
false),
979 KeyStatusPair(
"use-external-name",
false),
984 bool HasContents =
false;
985 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
986 std::string ExternalContentsPath;
988 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
997 if (!parseScalarString(
I->getKey(), Key,
Buffer))
1000 if (!checkDuplicateOrUnknownKey(
I->getKey(), Key, Keys))
1004 if (Key ==
"name") {
1008 }
else if (Key ==
"type") {
1011 if (Value ==
"file")
1013 else if (Value ==
"directory")
1014 Kind = EK_Directory;
1016 error(
I->getValue(),
"unknown value for 'type'");
1019 }
else if (Key ==
"contents") {
1022 "entry already has 'contents' or 'external-contents'");
1026 yaml::SequenceNode *Contents =
1027 dyn_cast<yaml::SequenceNode>(
I->getValue());
1030 error(
I->getValue(),
"expected array");
1035 E = Contents->end();
1037 if (std::unique_ptr<Entry> E = parseEntry(&*
I))
1038 EntryArrayContents.push_back(std::move(E));
1042 }
else if (Key ==
"external-contents") {
1045 "entry already has 'contents' or 'external-contents'");
1051 ExternalContentsPath =
Value;
1052 }
else if (Key ==
"use-external-name") {
1054 if (!parseScalarBool(
I->getValue(), Val))
1056 UseExternalName = Val ? RedirectingFileEntry::NK_External
1057 : RedirectingFileEntry::NK_Virtual;
1059 llvm_unreachable(
"key missing from Keys");
1063 if (Stream.failed())
1068 error(N,
"missing key 'contents' or 'external-contents'");
1071 if (!checkMissingKeys(N, Keys))
1075 if (Kind == EK_Directory &&
1076 UseExternalName != RedirectingFileEntry::NK_NotSet) {
1077 error(N,
"'use-external-name' is not supported for directories");
1082 StringRef Trimmed(Name);
1083 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1084 while (Trimmed.size() > RootPathLen &&
1085 sys::path::is_separator(Trimmed.back()))
1086 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1088 StringRef LastComponent = sys::path::filename(Trimmed);
1090 std::unique_ptr<Entry> Result;
1093 Result = llvm::make_unique<RedirectingFileEntry>(
1094 LastComponent, std::move(ExternalContentsPath), UseExternalName);
1097 Result = llvm::make_unique<RedirectingDirectoryEntry>(
1098 LastComponent, std::move(EntryArrayContents),
1100 file_type::directory_file, sys::fs::all_all));
1104 StringRef Parent = sys::path::parent_path(Trimmed);
1109 for (sys::path::reverse_iterator
I = sys::path::rbegin(Parent),
1110 E = sys::path::rend(Parent);
1112 std::vector<std::unique_ptr<Entry>> Entries;
1113 Entries.push_back(std::move(Result));
1114 Result = llvm::make_unique<RedirectingDirectoryEntry>(
1115 *
I, std::move(Entries),
1117 file_type::directory_file, sys::fs::all_all));
1123 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
1126 bool parse(
yaml::Node *Root, RedirectingFileSystem *FS) {
1127 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
1129 error(Root,
"expected mapping node");
1133 KeyStatusPair Fields[] = {
1134 KeyStatusPair(
"version",
true),
1135 KeyStatusPair(
"case-sensitive",
false),
1136 KeyStatusPair(
"use-external-names",
false),
1137 KeyStatusPair(
"roots",
true),
1147 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
1150 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
1153 if (Key ==
"roots") {
1154 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
1156 error(I->getValue(),
"expected array");
1162 if (std::unique_ptr<Entry> E = parseEntry(&*I))
1163 FS->Roots.push_back(std::move(E));
1167 }
else if (Key ==
"version") {
1168 StringRef VersionString;
1170 if (!parseScalarString(I->getValue(), VersionString, Storage))
1173 if (VersionString.getAsInteger<
int>(10, Version)) {
1174 error(I->getValue(),
"expected integer");
1178 error(I->getValue(),
"invalid version number");
1182 error(I->getValue(),
"version mismatch, expected 0");
1185 }
else if (Key ==
"case-sensitive") {
1186 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
1188 }
else if (Key ==
"use-external-names") {
1189 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
1192 llvm_unreachable(
"key missing from Keys");
1196 if (Stream.failed())
1199 if (!checkMissingKeys(Top, Keys))
1206 Entry::~Entry() =
default;
1209 std::unique_ptr<MemoryBuffer> Buffer, SourceMgr::DiagHandlerTy DiagHandler,
1213 yaml::Stream Stream(Buffer->getMemBufferRef(),
SM);
1215 SM.setDiagHandler(DiagHandler, DiagContext);
1216 yaml::document_iterator DI = Stream.begin();
1218 if (DI == Stream.end() || !Root) {
1219 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error,
"expected root node");
1223 RedirectingFileSystemParser
P(Stream);
1225 std::unique_ptr<RedirectingFileSystem> FS(
1226 new RedirectingFileSystem(ExternalFS));
1227 if (!
P.parse(Root, FS.get()))
1230 return FS.release();
1233 ErrorOr<Entry *> RedirectingFileSystem::lookupPath(
const Twine &Path_) {
1235 Path_.toVector(Path);
1238 if (std::error_code EC = makeAbsolute(Path))
1246 for (
const std::unique_ptr<Entry> &Root : Roots) {
1247 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
1248 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
1255 RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1256 sys::path::const_iterator End, Entry *From) {
1257 if (Start->equals(
"."))
1261 if (CaseSensitive ? !Start->equals(From->getName())
1262 : !Start->equals_lower(From->getName()))
1273 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
1277 for (
const std::unique_ptr<Entry> &DirEntry :
1278 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1279 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
1280 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
1288 Status S = ExternalStatus;
1289 if (!UseExternalNames)
1290 S = Status::copyWithNewName(S, Path.str());
1295 ErrorOr<Status> RedirectingFileSystem::status(
const Twine &Path, Entry *E) {
1296 assert(E !=
nullptr);
1297 if (
auto *F = dyn_cast<RedirectingFileEntry>(E)) {
1298 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
1299 assert(!S || S->getName() == F->getExternalContentsPath());
1305 auto *DE = cast<RedirectingDirectoryEntry>(
E);
1306 return Status::copyWithNewName(DE->getStatus(), Path.str());
1310 ErrorOr<Status> RedirectingFileSystem::status(
const Twine &Path) {
1311 ErrorOr<Entry *> Result = lookupPath(Path);
1313 return Result.getError();
1314 return status(Path, *Result);
1319 class FileWithFixedStatus :
public File {
1320 std::unique_ptr<File> InnerFile;
1324 FileWithFixedStatus(std::unique_ptr<File> InnerFile,
Status S)
1325 : InnerFile(std::move(InnerFile)), S(S) {}
1327 ErrorOr<Status>
status()
override {
return S; }
1328 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
1329 getBuffer(
const Twine &Name, int64_t FileSize,
bool RequiresNullTerminator,
1330 bool IsVolatile)
override {
1331 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1334 std::error_code
close()
override {
return InnerFile->close(); }
1338 ErrorOr<std::unique_ptr<File>>
1339 RedirectingFileSystem::openFileForRead(
const Twine &Path) {
1340 ErrorOr<Entry *> E = lookupPath(Path);
1342 return E.getError();
1344 auto *F = dyn_cast<RedirectingFileEntry>(*E);
1348 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1352 auto ExternalStatus = (*Result)->status();
1353 if (!ExternalStatus)
1354 return ExternalStatus.getError();
1359 return std::unique_ptr<File>(
1360 llvm::make_unique<FileWithFixedStatus>(std::move(*Result),
S));
1365 SourceMgr::DiagHandlerTy DiagHandler,
void *DiagContext,
1368 DiagContext, ExternalFS);
1372 static std::atomic<unsigned> UID;
1373 unsigned ID = ++UID;
1376 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1381 using namespace llvm::sys;
1383 if (Comp ==
"." || Comp ==
"..")
1389 void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1390 assert(sys::path::is_absolute(VirtualPath) &&
"virtual path not absolute");
1391 assert(sys::path::is_absolute(RealPath) &&
"real path not absolute");
1392 assert(!
pathHasTraversal(VirtualPath) &&
"path traversal is not supported");
1393 Mappings.emplace_back(VirtualPath, RealPath);
1398 llvm::raw_ostream &OS;
1400 inline unsigned getDirIndent() {
return 4 * DirStack.size(); }
1401 inline unsigned getFileIndent() {
return 4 * (DirStack.size() + 1); }
1402 bool containedIn(StringRef Parent, StringRef Path);
1403 StringRef containedPart(StringRef Parent, StringRef Path);
1404 void startDirectory(StringRef Path);
1405 void endDirectory();
1406 void writeEntry(StringRef VPath, StringRef RPath);
1409 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
1414 bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
1415 using namespace llvm::sys;
1419 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1420 if (*IParent != *IChild)
1424 return IParent == EParent;
1427 StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1428 assert(!Parent.empty());
1429 assert(containedIn(Parent, Path));
1430 return Path.slice(Parent.size() + 1, StringRef::npos);
1433 void JSONWriter::startDirectory(StringRef Path) {
1435 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1436 DirStack.push_back(Path);
1437 unsigned Indent = getDirIndent();
1438 OS.indent(Indent) <<
"{\n";
1439 OS.indent(Indent + 2) <<
"'type': 'directory',\n";
1440 OS.indent(Indent + 2) <<
"'name': \"" << llvm::yaml::escape(Name) <<
"\",\n";
1441 OS.indent(Indent + 2) <<
"'contents': [\n";
1444 void JSONWriter::endDirectory() {
1445 unsigned Indent = getDirIndent();
1446 OS.indent(Indent + 2) <<
"]\n";
1447 OS.indent(Indent) <<
"}";
1449 DirStack.pop_back();
1452 void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1453 unsigned Indent = getFileIndent();
1454 OS.indent(Indent) <<
"{\n";
1455 OS.indent(Indent + 2) <<
"'type': 'file',\n";
1456 OS.indent(Indent + 2) <<
"'name': \"" << llvm::yaml::escape(VPath) <<
"\",\n";
1457 OS.indent(Indent + 2) <<
"'external-contents': \""
1458 << llvm::yaml::escape(RPath) <<
"\"\n";
1459 OS.indent(Indent) <<
"}";
1464 using namespace llvm::sys;
1468 if (IsCaseSensitive.hasValue())
1469 OS <<
" 'case-sensitive': '"
1470 << (IsCaseSensitive.getValue() ?
"true" :
"false") <<
"',\n";
1471 OS <<
" 'roots': [\n";
1473 if (!Entries.empty()) {
1475 startDirectory(path::parent_path(Entry.
VPath));
1476 writeEntry(path::filename(Entry.
VPath), Entry.
RPath);
1478 for (
const auto &Entry : Entries.slice(1)) {
1479 StringRef Dir = path::parent_path(Entry.
VPath);
1480 if (Dir == DirStack.back())
1483 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1488 startDirectory(Dir);
1490 writeEntry(path::filename(Entry.
VPath), Entry.
RPath);
1493 while (!DirStack.empty()) {
1505 std::sort(Mappings.begin(), Mappings.end(),
1507 return LHS.
VPath < RHS.VPath;
1510 JSONWriter(OS).write(Mappings, IsCaseSensitive);
1513 VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1514 const Twine &_Path, RedirectingFileSystem &FS,
1517 : Dir(_Path.str()), FS(FS),
Current(Begin), End(End) {
1520 llvm::sys::path::append(PathStr, (*Current)->getName());
1521 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
1529 std::error_code VFSFromYamlDirIterImpl::increment() {
1530 assert(
Current != End &&
"cannot iterate past end");
1533 llvm::sys::path::append(PathStr, (*Current)->getName());
1534 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
1536 return S.getError();
1541 return std::error_code();
1546 std::error_code &EC)
1550 State = std::make_shared<IterState>();
1557 assert(FS && State && !State->empty() &&
"incrementing past end");
1558 assert(State->top()->isStatusKnown() &&
"non-canonical end iterator");
1560 if (State->top()->isDirectory()) {
1570 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.
IntrusiveRefCntPtr< FileSystem > getVFSFromYAML(std::unique_ptr< llvm::MemoryBuffer > Buffer, llvm::SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext=nullptr, IntrusiveRefCntPtr< FileSystem > ExternalFS=getRealFileSystem())
Gets a FileSystem for a virtual file system described in YAML format.
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.
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
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.
ID
Defines the set of possible language-specific address spaces.
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)
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
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.