1 //===- VirtualFileSystem.cpp - Virtual File System Layer --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 // This file implements the VirtualFileSystem interface.
10 //===----------------------------------------------------------------------===//
12 #include "clang/Basic/VirtualFileSystem.h"
13 #include "clang/Basic/FileManager.h"
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"
30 using namespace clang;
31 using namespace clang::vfs;
33 using llvm::sys::fs::file_status;
34 using llvm::sys::fs::file_type;
35 using llvm::sys::fs::perms;
36 using llvm::sys::fs::UniqueID;
38 Status::Status(const file_status &Status)
39 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
40 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
41 Type(Status.type()), Perms(Status.permissions()), IsVFSMapped(false) {}
43 Status::Status(StringRef Name, UniqueID UID, sys::TimePoint<> MTime,
44 uint32_t User, uint32_t Group, uint64_t Size, file_type Type,
46 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
47 Type(Type), Perms(Perms), IsVFSMapped(false) {}
49 Status Status::copyWithNewName(const Status &In, StringRef NewName) {
50 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
51 In.getUser(), In.getGroup(), In.getSize(), In.getType(),
55 Status Status::copyWithNewName(const file_status &In, StringRef NewName) {
56 return Status(NewName, In.getUniqueID(), In.getLastModificationTime(),
57 In.getUser(), In.getGroup(), In.getSize(), In.type(),
61 bool Status::equivalent(const Status &Other) const {
62 assert(isStatusKnown() && Other.isStatusKnown());
63 return getUniqueID() == Other.getUniqueID();
65 bool Status::isDirectory() const {
66 return Type == file_type::directory_file;
68 bool Status::isRegularFile() const {
69 return Type == file_type::regular_file;
71 bool Status::isOther() const {
72 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
74 bool Status::isSymlink() const {
75 return Type == file_type::symlink_file;
77 bool Status::isStatusKnown() const {
78 return Type != file_type::status_error;
80 bool Status::exists() const {
81 return isStatusKnown() && Type != file_type::file_not_found;
86 FileSystem::~FileSystem() {}
88 ErrorOr<std::unique_ptr<MemoryBuffer>>
89 FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
90 bool RequiresNullTerminator, bool IsVolatile) {
91 auto F = openFileForRead(Name);
95 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
98 std::error_code FileSystem::makeAbsolute(SmallVectorImpl<char> &Path) const {
99 if (llvm::sys::path::is_absolute(Path))
100 return std::error_code();
102 auto WorkingDir = getCurrentWorkingDirectory();
104 return WorkingDir.getError();
106 return llvm::sys::fs::make_absolute(WorkingDir.get(), Path);
109 bool FileSystem::exists(const Twine &Path) {
110 auto Status = status(Path);
111 return Status && Status->exists();
115 static bool isTraversalComponent(StringRef Component) {
116 return Component.equals("..") || Component.equals(".");
119 static bool pathHasTraversal(StringRef Path) {
120 using namespace llvm::sys;
121 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
122 if (isTraversalComponent(Comp))
128 //===-----------------------------------------------------------------------===/
129 // RealFileSystem implementation
130 //===-----------------------------------------------------------------------===/
133 /// \brief Wrapper around a raw file descriptor.
134 class RealFile : public File {
137 std::string RealName;
138 friend class RealFileSystem;
139 RealFile(int FD, StringRef NewName, StringRef NewRealPathName)
140 : FD(FD), S(NewName, {}, {}, {}, {}, {},
141 llvm::sys::fs::file_type::status_error, {}),
142 RealName(NewRealPathName.str()) {
143 assert(FD >= 0 && "Invalid or inactive file descriptor");
147 ~RealFile() override;
148 ErrorOr<Status> status() override;
149 ErrorOr<std::string> getName() override;
150 ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name,
152 bool RequiresNullTerminator,
153 bool IsVolatile) override;
154 std::error_code close() override;
156 } // end anonymous namespace
157 RealFile::~RealFile() { close(); }
159 ErrorOr<Status> RealFile::status() {
160 assert(FD != -1 && "cannot stat closed file");
161 if (!S.isStatusKnown()) {
162 file_status RealStatus;
163 if (std::error_code EC = sys::fs::status(FD, RealStatus))
165 S = Status::copyWithNewName(RealStatus, S.getName());
170 ErrorOr<std::string> RealFile::getName() {
171 return RealName.empty() ? S.getName().str() : RealName;
174 ErrorOr<std::unique_ptr<MemoryBuffer>>
175 RealFile::getBuffer(const Twine &Name, int64_t FileSize,
176 bool RequiresNullTerminator, bool IsVolatile) {
177 assert(FD != -1 && "cannot get buffer for closed file");
178 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
182 std::error_code RealFile::close() {
183 std::error_code EC = sys::Process::SafelyCloseFileDescriptor(FD);
189 /// \brief The file system according to your operating system.
190 class RealFileSystem : public FileSystem {
192 ErrorOr<Status> status(const Twine &Path) override;
193 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
194 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
196 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override;
197 std::error_code setCurrentWorkingDirectory(const Twine &Path) override;
199 } // end anonymous namespace
201 ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
202 sys::fs::file_status RealStatus;
203 if (std::error_code EC = sys::fs::status(Path, RealStatus))
205 return Status::copyWithNewName(RealStatus, Path.str());
208 ErrorOr<std::unique_ptr<File>>
209 RealFileSystem::openFileForRead(const Twine &Name) {
211 SmallString<256> RealName;
212 if (std::error_code EC = sys::fs::openFileForRead(Name, FD, &RealName))
214 return std::unique_ptr<File>(new RealFile(FD, Name.str(), RealName.str()));
217 llvm::ErrorOr<std::string> RealFileSystem::getCurrentWorkingDirectory() const {
218 SmallString<256> Dir;
219 if (std::error_code EC = llvm::sys::fs::current_path(Dir))
221 return Dir.str().str();
224 std::error_code RealFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
225 // FIXME: chdir is thread hostile; on the other hand, creating the same
226 // behavior as chdir is complex: chdir resolves the path once, thus
227 // guaranteeing that all subsequent relative path operations work
228 // on the same path the original chdir resulted in. This makes a
229 // difference for example on network filesystems, where symlinks might be
230 // switched during runtime of the tool. Fixing this depends on having a
231 // file system abstraction that allows openat() style interactions.
232 return llvm::sys::fs::set_current_path(Path);
235 IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
236 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
241 class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
242 llvm::sys::fs::directory_iterator Iter;
244 RealFSDirIter(const Twine &Path, std::error_code &EC) : Iter(Path, EC) {
245 if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
246 llvm::sys::fs::file_status S;
247 EC = llvm::sys::fs::status(Iter->path(), S, true);
248 CurrentEntry = Status::copyWithNewName(S, Iter->path());
252 std::error_code increment() override {
257 } else if (Iter == llvm::sys::fs::directory_iterator()) {
258 CurrentEntry = Status();
260 llvm::sys::fs::file_status S;
261 EC = llvm::sys::fs::status(Iter->path(), S, true);
262 CurrentEntry = Status::copyWithNewName(S, Iter->path());
269 directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
270 std::error_code &EC) {
271 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
274 //===-----------------------------------------------------------------------===/
275 // OverlayFileSystem implementation
276 //===-----------------------------------------------------------------------===/
277 OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
278 FSList.push_back(std::move(BaseFS));
281 void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
282 FSList.push_back(FS);
283 // Synchronize added file systems by duplicating the working directory from
284 // the first one in the list.
285 FS->setCurrentWorkingDirectory(getCurrentWorkingDirectory().get());
288 ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
289 // FIXME: handle symlinks that cross file systems
290 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
291 ErrorOr<Status> Status = (*I)->status(Path);
292 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
295 return make_error_code(llvm::errc::no_such_file_or_directory);
298 ErrorOr<std::unique_ptr<File>>
299 OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
300 // FIXME: handle symlinks that cross file systems
301 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
302 auto Result = (*I)->openFileForRead(Path);
303 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
306 return make_error_code(llvm::errc::no_such_file_or_directory);
309 llvm::ErrorOr<std::string>
310 OverlayFileSystem::getCurrentWorkingDirectory() const {
311 // All file systems are synchronized, just take the first working directory.
312 return FSList.front()->getCurrentWorkingDirectory();
315 OverlayFileSystem::setCurrentWorkingDirectory(const Twine &Path) {
316 for (auto &FS : FSList)
317 if (std::error_code EC = FS->setCurrentWorkingDirectory(Path))
319 return std::error_code();
322 clang::vfs::detail::DirIterImpl::~DirIterImpl() { }
325 class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
326 OverlayFileSystem &Overlays;
328 OverlayFileSystem::iterator CurrentFS;
329 directory_iterator CurrentDirIter;
330 llvm::StringSet<> SeenNames;
332 std::error_code incrementFS() {
333 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
335 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
337 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
338 if (EC && EC != errc::no_such_file_or_directory)
340 if (CurrentDirIter != directory_iterator())
343 return std::error_code();
346 std::error_code incrementDirIter(bool IsFirstTime) {
347 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
348 "incrementing past end");
351 CurrentDirIter.increment(EC);
352 if (!EC && CurrentDirIter == directory_iterator())
357 std::error_code incrementImpl(bool IsFirstTime) {
359 std::error_code EC = incrementDirIter(IsFirstTime);
360 if (EC || CurrentDirIter == directory_iterator()) {
361 CurrentEntry = Status();
364 CurrentEntry = *CurrentDirIter;
365 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
366 if (SeenNames.insert(Name).second)
367 return EC; // name not seen before
369 llvm_unreachable("returned above");
373 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
375 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
376 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
377 EC = incrementImpl(true);
380 std::error_code increment() override { return incrementImpl(false); }
382 } // end anonymous namespace
384 directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
385 std::error_code &EC) {
386 return directory_iterator(
387 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
394 enum InMemoryNodeKind { IME_File, IME_Directory };
396 /// The in memory file system is a tree of Nodes. Every node can either be a
397 /// file or a directory.
400 InMemoryNodeKind Kind;
403 InMemoryNode(Status Stat, InMemoryNodeKind Kind)
404 : Stat(std::move(Stat)), Kind(Kind) {}
405 virtual ~InMemoryNode() {}
406 const Status &getStatus() const { return Stat; }
407 InMemoryNodeKind getKind() const { return Kind; }
408 virtual std::string toString(unsigned Indent) const = 0;
412 class InMemoryFile : public InMemoryNode {
413 std::unique_ptr<llvm::MemoryBuffer> Buffer;
416 InMemoryFile(Status Stat, std::unique_ptr<llvm::MemoryBuffer> Buffer)
417 : InMemoryNode(std::move(Stat), IME_File), Buffer(std::move(Buffer)) {}
419 llvm::MemoryBuffer *getBuffer() { return Buffer.get(); }
420 std::string toString(unsigned Indent) const override {
421 return (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
423 static bool classof(const InMemoryNode *N) {
424 return N->getKind() == IME_File;
428 /// Adapt a InMemoryFile for VFS' File interface.
429 class InMemoryFileAdaptor : public File {
433 explicit InMemoryFileAdaptor(InMemoryFile &Node) : Node(Node) {}
435 llvm::ErrorOr<Status> status() override { return Node.getStatus(); }
436 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
437 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
438 bool IsVolatile) override {
439 llvm::MemoryBuffer *Buf = Node.getBuffer();
440 return llvm::MemoryBuffer::getMemBuffer(
441 Buf->getBuffer(), Buf->getBufferIdentifier(), RequiresNullTerminator);
443 std::error_code close() override { return std::error_code(); }
445 } // end anonymous namespace
447 class InMemoryDirectory : public InMemoryNode {
448 std::map<std::string, std::unique_ptr<InMemoryNode>> Entries;
451 InMemoryDirectory(Status Stat)
452 : InMemoryNode(std::move(Stat), IME_Directory) {}
453 InMemoryNode *getChild(StringRef Name) {
454 auto I = Entries.find(Name);
455 if (I != Entries.end())
456 return I->second.get();
459 InMemoryNode *addChild(StringRef Name, std::unique_ptr<InMemoryNode> Child) {
460 return Entries.insert(make_pair(Name, std::move(Child)))
461 .first->second.get();
464 typedef decltype(Entries)::const_iterator const_iterator;
465 const_iterator begin() const { return Entries.begin(); }
466 const_iterator end() const { return Entries.end(); }
468 std::string toString(unsigned Indent) const override {
470 (std::string(Indent, ' ') + getStatus().getName() + "\n").str();
471 for (const auto &Entry : Entries) {
472 Result += Entry.second->toString(Indent + 2);
476 static bool classof(const InMemoryNode *N) {
477 return N->getKind() == IME_Directory;
482 InMemoryFileSystem::InMemoryFileSystem(bool UseNormalizedPaths)
483 : Root(new detail::InMemoryDirectory(
484 Status("", getNextVirtualUniqueID(), llvm::sys::TimePoint<>(), 0, 0,
485 0, llvm::sys::fs::file_type::directory_file,
486 llvm::sys::fs::perms::all_all))),
487 UseNormalizedPaths(UseNormalizedPaths) {}
489 InMemoryFileSystem::~InMemoryFileSystem() {}
491 std::string InMemoryFileSystem::toString() const {
492 return Root->toString(/*Indent=*/0);
495 bool InMemoryFileSystem::addFile(const Twine &P, time_t ModificationTime,
496 std::unique_ptr<llvm::MemoryBuffer> Buffer,
497 Optional<uint32_t> User,
498 Optional<uint32_t> Group,
499 Optional<llvm::sys::fs::file_type> Type,
500 Optional<llvm::sys::fs::perms> Perms) {
501 SmallString<128> Path;
504 // Fix up relative paths. This just prepends the current working directory.
505 std::error_code EC = makeAbsolute(Path);
509 if (useNormalizedPaths())
510 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
515 detail::InMemoryDirectory *Dir = Root.get();
516 auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path);
517 const auto ResolvedUser = User.getValueOr(0);
518 const auto ResolvedGroup = Group.getValueOr(0);
519 const auto ResolvedType = Type.getValueOr(sys::fs::file_type::regular_file);
520 const auto ResolvedPerms = Perms.getValueOr(sys::fs::all_all);
521 // Any intermediate directories we create should be accessible by
522 // the owner, even if Perms says otherwise for the final path.
523 const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all;
526 detail::InMemoryNode *Node = Dir->getChild(Name);
530 // End of the path, create a new file or directory.
531 Status Stat(P.str(), getNextVirtualUniqueID(),
532 llvm::sys::toTimePoint(ModificationTime), ResolvedUser,
533 ResolvedGroup, Buffer->getBufferSize(), ResolvedType,
535 std::unique_ptr<detail::InMemoryNode> Child;
536 if (ResolvedType == sys::fs::file_type::directory_file) {
537 Child.reset(new detail::InMemoryDirectory(std::move(Stat)));
539 Child.reset(new detail::InMemoryFile(std::move(Stat),
542 Dir->addChild(Name, std::move(Child));
546 // Create a new directory. Use the path up to here.
548 StringRef(Path.str().begin(), Name.end() - Path.str().begin()),
549 getNextVirtualUniqueID(), llvm::sys::toTimePoint(ModificationTime),
550 ResolvedUser, ResolvedGroup, Buffer->getBufferSize(),
551 sys::fs::file_type::directory_file, NewDirectoryPerms);
552 Dir = cast<detail::InMemoryDirectory>(Dir->addChild(
553 Name, llvm::make_unique<detail::InMemoryDirectory>(std::move(Stat))));
557 if (auto *NewDir = dyn_cast<detail::InMemoryDirectory>(Node)) {
560 assert(isa<detail::InMemoryFile>(Node) &&
561 "Must be either file or directory!");
563 // Trying to insert a directory in place of a file.
567 // Return false only if the new file is different from the existing one.
568 return cast<detail::InMemoryFile>(Node)->getBuffer()->getBuffer() ==
574 bool InMemoryFileSystem::addFileNoOwn(const Twine &P, time_t ModificationTime,
575 llvm::MemoryBuffer *Buffer,
576 Optional<uint32_t> User,
577 Optional<uint32_t> Group,
578 Optional<llvm::sys::fs::file_type> Type,
579 Optional<llvm::sys::fs::perms> Perms) {
580 return addFile(P, ModificationTime,
581 llvm::MemoryBuffer::getMemBuffer(
582 Buffer->getBuffer(), Buffer->getBufferIdentifier()),
583 std::move(User), std::move(Group), std::move(Type),
587 static ErrorOr<detail::InMemoryNode *>
588 lookupInMemoryNode(const InMemoryFileSystem &FS, detail::InMemoryDirectory *Dir,
590 SmallString<128> Path;
593 // Fix up relative paths. This just prepends the current working directory.
594 std::error_code EC = FS.makeAbsolute(Path);
598 if (FS.useNormalizedPaths())
599 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
604 auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
606 detail::InMemoryNode *Node = Dir->getChild(*I);
609 return errc::no_such_file_or_directory;
611 // Return the file if it's at the end of the path.
612 if (auto File = dyn_cast<detail::InMemoryFile>(Node)) {
615 return errc::no_such_file_or_directory;
618 // Traverse directories.
619 Dir = cast<detail::InMemoryDirectory>(Node);
625 llvm::ErrorOr<Status> InMemoryFileSystem::status(const Twine &Path) {
626 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
628 return (*Node)->getStatus();
629 return Node.getError();
632 llvm::ErrorOr<std::unique_ptr<File>>
633 InMemoryFileSystem::openFileForRead(const Twine &Path) {
634 auto Node = lookupInMemoryNode(*this, Root.get(), Path);
636 return Node.getError();
638 // When we have a file provide a heap-allocated wrapper for the memory buffer
639 // to match the ownership semantics for File.
640 if (auto *F = dyn_cast<detail::InMemoryFile>(*Node))
641 return std::unique_ptr<File>(new detail::InMemoryFileAdaptor(*F));
643 // FIXME: errc::not_a_file?
644 return make_error_code(llvm::errc::invalid_argument);
648 /// Adaptor from InMemoryDir::iterator to directory_iterator.
649 class InMemoryDirIterator : public clang::vfs::detail::DirIterImpl {
650 detail::InMemoryDirectory::const_iterator I;
651 detail::InMemoryDirectory::const_iterator E;
654 InMemoryDirIterator() {}
655 explicit InMemoryDirIterator(detail::InMemoryDirectory &Dir)
656 : I(Dir.begin()), E(Dir.end()) {
658 CurrentEntry = I->second->getStatus();
661 std::error_code increment() override {
663 // When we're at the end, make CurrentEntry invalid and DirIterImpl will do
665 CurrentEntry = I != E ? I->second->getStatus() : Status();
666 return std::error_code();
669 } // end anonymous namespace
671 directory_iterator InMemoryFileSystem::dir_begin(const Twine &Dir,
672 std::error_code &EC) {
673 auto Node = lookupInMemoryNode(*this, Root.get(), Dir);
675 EC = Node.getError();
676 return directory_iterator(std::make_shared<InMemoryDirIterator>());
679 if (auto *DirNode = dyn_cast<detail::InMemoryDirectory>(*Node))
680 return directory_iterator(std::make_shared<InMemoryDirIterator>(*DirNode));
682 EC = make_error_code(llvm::errc::not_a_directory);
683 return directory_iterator(std::make_shared<InMemoryDirIterator>());
686 std::error_code InMemoryFileSystem::setCurrentWorkingDirectory(const Twine &P) {
687 SmallString<128> Path;
690 // Fix up relative paths. This just prepends the current working directory.
691 std::error_code EC = makeAbsolute(Path);
695 if (useNormalizedPaths())
696 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
699 WorkingDirectory = Path.str();
700 return std::error_code();
705 //===-----------------------------------------------------------------------===/
706 // RedirectingFileSystem implementation
707 //===-----------------------------------------------------------------------===/
716 /// \brief A single file or directory in the VFS.
723 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
724 StringRef getName() const { return Name; }
725 EntryKind getKind() const { return Kind; }
728 class RedirectingDirectoryEntry : public Entry {
729 std::vector<std::unique_ptr<Entry>> Contents;
733 RedirectingDirectoryEntry(StringRef Name,
734 std::vector<std::unique_ptr<Entry>> Contents,
736 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
738 RedirectingDirectoryEntry(StringRef Name, Status S)
739 : Entry(EK_Directory, Name), S(std::move(S)) {}
740 Status getStatus() { return S; }
741 void addContent(std::unique_ptr<Entry> Content) {
742 Contents.push_back(std::move(Content));
744 Entry *getLastContent() const { return Contents.back().get(); }
745 typedef decltype(Contents)::iterator iterator;
746 iterator contents_begin() { return Contents.begin(); }
747 iterator contents_end() { return Contents.end(); }
748 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
751 class RedirectingFileEntry : public Entry {
759 std::string ExternalContentsPath;
762 RedirectingFileEntry(StringRef Name, StringRef ExternalContentsPath,
764 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
766 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
767 /// \brief whether to use the external path as the name for this file.
768 bool useExternalName(bool GlobalUseExternalName) const {
769 return UseName == NK_NotSet ? GlobalUseExternalName
770 : (UseName == NK_External);
772 NameKind getUseName() const { return UseName; }
773 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
776 class RedirectingFileSystem;
778 class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
780 RedirectingFileSystem &FS;
781 RedirectingDirectoryEntry::iterator Current, End;
784 VFSFromYamlDirIterImpl(const Twine &Path, RedirectingFileSystem &FS,
785 RedirectingDirectoryEntry::iterator Begin,
786 RedirectingDirectoryEntry::iterator End,
787 std::error_code &EC);
788 std::error_code increment() override;
791 /// \brief A virtual file system parsed from a YAML file.
793 /// Currently, this class allows creating virtual directories and mapping
794 /// virtual file paths to existing external files, available in \c ExternalFS.
796 /// The basic structure of the parsed file is:
799 /// 'version': <version number>,
800 /// <optional configuration>
802 /// <directory entries>
807 /// All configuration options are optional.
808 /// 'case-sensitive': <boolean, default=true>
809 /// 'use-external-names': <boolean, default=true>
810 /// 'overlay-relative': <boolean, default=false>
811 /// 'ignore-non-existent-contents': <boolean, default=true>
813 /// Virtual directories are represented as
816 /// 'type': 'directory',
817 /// 'name': <string>,
818 /// 'contents': [ <file or directory entries> ]
822 /// The default attributes for virtual directories are:
824 /// MTime = now() when created
828 /// UniqueID = unspecified unique value
831 /// Re-mapped files are represented as
835 /// 'name': <string>,
836 /// 'use-external-name': <boolean> # Optional
837 /// 'external-contents': <path to external file>)
841 /// and inherit their attributes from the external contents.
843 /// In both cases, the 'name' field may contain multiple path components (e.g.
844 /// /path/to/file). However, any directory that contains more than one child
845 /// must be uniquely represented by a directory entry.
846 class RedirectingFileSystem : public vfs::FileSystem {
847 /// The root(s) of the virtual file system.
848 std::vector<std::unique_ptr<Entry>> Roots;
849 /// \brief The file system to use for external references.
850 IntrusiveRefCntPtr<FileSystem> ExternalFS;
851 /// If IsRelativeOverlay is set, this represents the directory
852 /// path that should be prefixed to each 'external-contents' entry
853 /// when reading from YAML files.
854 std::string ExternalContentsPrefixDir;
856 /// @name Configuration
859 /// \brief Whether to perform case-sensitive comparisons.
861 /// Currently, case-insensitive matching only works correctly with ASCII.
862 bool CaseSensitive = true;
864 /// IsRelativeOverlay marks whether a IsExternalContentsPrefixDir path must
865 /// be prefixed in every 'external-contents' when reading from YAML files.
866 bool IsRelativeOverlay = false;
868 /// \brief Whether to use to use the value of 'external-contents' for the
869 /// names of files. This global value is overridable on a per-file basis.
870 bool UseExternalNames = true;
872 /// \brief Whether an invalid path obtained via 'external-contents' should
873 /// cause iteration on the VFS to stop. If 'true', the VFS should ignore
874 /// the entry and continue with the next. Allows YAML files to be shared
875 /// across multiple compiler invocations regardless of prior existent
876 /// paths in 'external-contents'. This global value is overridable on a
878 bool IgnoreNonExistentContents = true;
881 /// Virtual file paths and external files could be canonicalized without "..",
882 /// "." and "./" in their paths. FIXME: some unittests currently fail on
883 /// win32 when using remove_dots and remove_leading_dotslash on paths.
884 bool UseCanonicalizedPaths =
891 friend class RedirectingFileSystemParser;
894 RedirectingFileSystem(IntrusiveRefCntPtr<FileSystem> ExternalFS)
895 : ExternalFS(std::move(ExternalFS)) {}
897 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
898 /// recursing into the contents of \p From if it is a directory.
899 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
900 sys::path::const_iterator End, Entry *From);
902 /// \brief Get the status of a given an \c Entry.
903 ErrorOr<Status> status(const Twine &Path, Entry *E);
906 /// \brief Looks up \p Path in \c Roots.
907 ErrorOr<Entry *> lookupPath(const Twine &Path);
909 /// \brief Parses \p Buffer, which is expected to be in YAML format and
910 /// returns a virtual file system representing its contents.
911 static RedirectingFileSystem *
912 create(std::unique_ptr<MemoryBuffer> Buffer,
913 SourceMgr::DiagHandlerTy DiagHandler, StringRef YAMLFilePath,
914 void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS);
916 ErrorOr<Status> status(const Twine &Path) override;
917 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
919 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
920 return ExternalFS->getCurrentWorkingDirectory();
922 std::error_code setCurrentWorkingDirectory(const Twine &Path) override {
923 return ExternalFS->setCurrentWorkingDirectory(Path);
926 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
927 ErrorOr<Entry *> E = lookupPath(Dir);
930 return directory_iterator();
932 ErrorOr<Status> S = status(Dir, *E);
935 return directory_iterator();
937 if (!S->isDirectory()) {
938 EC = std::error_code(static_cast<int>(errc::not_a_directory),
939 std::system_category());
940 return directory_iterator();
943 auto *D = cast<RedirectingDirectoryEntry>(*E);
944 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
945 *this, D->contents_begin(), D->contents_end(), EC));
948 void setExternalContentsPrefixDir(StringRef PrefixDir) {
949 ExternalContentsPrefixDir = PrefixDir.str();
952 StringRef getExternalContentsPrefixDir() const {
953 return ExternalContentsPrefixDir;
956 bool ignoreNonExistentContents() const {
957 return IgnoreNonExistentContents;
960 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
961 LLVM_DUMP_METHOD void dump() const {
962 for (const std::unique_ptr<Entry> &Root : Roots)
963 dumpEntry(Root.get());
966 LLVM_DUMP_METHOD void dumpEntry(Entry *E, int NumSpaces = 0) const {
967 StringRef Name = E->getName();
968 for (int i = 0, e = NumSpaces; i < e; ++i)
970 dbgs() << "'" << Name.str().c_str() << "'" << "\n";
972 if (E->getKind() == EK_Directory) {
973 auto *DE = dyn_cast<RedirectingDirectoryEntry>(E);
974 assert(DE && "Should be a directory");
976 for (std::unique_ptr<Entry> &SubEntry :
977 llvm::make_range(DE->contents_begin(), DE->contents_end()))
978 dumpEntry(SubEntry.get(), NumSpaces+2);
985 /// \brief A helper class to hold the common YAML parsing state.
986 class RedirectingFileSystemParser {
987 yaml::Stream &Stream;
989 void error(yaml::Node *N, const Twine &Msg) {
990 Stream.printError(N, Msg);
994 bool parseScalarString(yaml::Node *N, StringRef &Result,
995 SmallVectorImpl<char> &Storage) {
996 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
998 error(N, "expected string");
1001 Result = S->getValue(Storage);
1006 bool parseScalarBool(yaml::Node *N, bool &Result) {
1007 SmallString<5> Storage;
1009 if (!parseScalarString(N, Value, Storage))
1012 if (Value.equals_lower("true") || Value.equals_lower("on") ||
1013 Value.equals_lower("yes") || Value == "1") {
1016 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
1017 Value.equals_lower("no") || Value == "0") {
1022 error(N, "expected boolean value");
1027 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
1031 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
1034 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
1035 DenseMap<StringRef, KeyStatus> &Keys) {
1036 if (!Keys.count(Key)) {
1037 error(KeyNode, "unknown key");
1040 KeyStatus &S = Keys[Key];
1042 error(KeyNode, Twine("duplicate key '") + Key + "'");
1050 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
1051 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
1054 if (I->second.Required && !I->second.Seen) {
1055 error(Obj, Twine("missing key '") + I->first + "'");
1062 Entry *lookupOrCreateEntry(RedirectingFileSystem *FS, StringRef Name,
1063 Entry *ParentEntry = nullptr) {
1064 if (!ParentEntry) { // Look for a existent root
1065 for (const std::unique_ptr<Entry> &Root : FS->Roots) {
1066 if (Name.equals(Root->getName())) {
1067 ParentEntry = Root.get();
1071 } else { // Advance to the next component
1072 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1073 for (std::unique_ptr<Entry> &Content :
1074 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1075 auto *DirContent = dyn_cast<RedirectingDirectoryEntry>(Content.get());
1076 if (DirContent && Name.equals(Content->getName()))
1081 // ... or create a new one
1082 std::unique_ptr<Entry> E = llvm::make_unique<RedirectingDirectoryEntry>(
1084 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1085 0, 0, 0, file_type::directory_file, sys::fs::all_all));
1087 if (!ParentEntry) { // Add a new root to the overlay
1088 FS->Roots.push_back(std::move(E));
1089 ParentEntry = FS->Roots.back().get();
1093 auto *DE = dyn_cast<RedirectingDirectoryEntry>(ParentEntry);
1094 DE->addContent(std::move(E));
1095 return DE->getLastContent();
1098 void uniqueOverlayTree(RedirectingFileSystem *FS, Entry *SrcE,
1099 Entry *NewParentE = nullptr) {
1100 StringRef Name = SrcE->getName();
1101 switch (SrcE->getKind()) {
1102 case EK_Directory: {
1103 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1104 assert(DE && "Must be a directory");
1105 // Empty directories could be present in the YAML as a way to
1106 // describe a file for a current directory after some of its subdir
1107 // is parsed. This only leads to redundant walks, ignore it.
1109 NewParentE = lookupOrCreateEntry(FS, Name, NewParentE);
1110 for (std::unique_ptr<Entry> &SubEntry :
1111 llvm::make_range(DE->contents_begin(), DE->contents_end()))
1112 uniqueOverlayTree(FS, SubEntry.get(), NewParentE);
1116 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1117 assert(FE && "Must be a file");
1118 assert(NewParentE && "Parent entry must exist");
1119 auto *DE = dyn_cast<RedirectingDirectoryEntry>(NewParentE);
1120 DE->addContent(llvm::make_unique<RedirectingFileEntry>(
1121 Name, FE->getExternalContentsPath(), FE->getUseName()));
1127 std::unique_ptr<Entry> parseEntry(yaml::Node *N, RedirectingFileSystem *FS) {
1128 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
1130 error(N, "expected mapping node for file or directory entry");
1134 KeyStatusPair Fields[] = {
1135 KeyStatusPair("name", true),
1136 KeyStatusPair("type", true),
1137 KeyStatusPair("contents", false),
1138 KeyStatusPair("external-contents", false),
1139 KeyStatusPair("use-external-name", false),
1142 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
1144 bool HasContents = false; // external or otherwise
1145 std::vector<std::unique_ptr<Entry>> EntryArrayContents;
1146 std::string ExternalContentsPath;
1148 auto UseExternalName = RedirectingFileEntry::NK_NotSet;
1151 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
1154 // Reuse the buffer for key and value, since we don't look at key after
1156 SmallString<256> Buffer;
1157 if (!parseScalarString(I->getKey(), Key, Buffer))
1160 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
1164 if (Key == "name") {
1165 if (!parseScalarString(I->getValue(), Value, Buffer))
1168 if (FS->UseCanonicalizedPaths) {
1169 SmallString<256> Path(Value);
1170 // Guarantee that old YAML files containing paths with ".." and "."
1171 // are properly canonicalized before read into the VFS.
1172 Path = sys::path::remove_leading_dotslash(Path);
1173 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1178 } else if (Key == "type") {
1179 if (!parseScalarString(I->getValue(), Value, Buffer))
1181 if (Value == "file")
1183 else if (Value == "directory")
1184 Kind = EK_Directory;
1186 error(I->getValue(), "unknown value for 'type'");
1189 } else if (Key == "contents") {
1192 "entry already has 'contents' or 'external-contents'");
1196 yaml::SequenceNode *Contents =
1197 dyn_cast<yaml::SequenceNode>(I->getValue());
1199 // FIXME: this is only for directories, what about files?
1200 error(I->getValue(), "expected array");
1204 for (yaml::SequenceNode::iterator I = Contents->begin(),
1205 E = Contents->end();
1207 if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
1208 EntryArrayContents.push_back(std::move(E));
1212 } else if (Key == "external-contents") {
1215 "entry already has 'contents' or 'external-contents'");
1219 if (!parseScalarString(I->getValue(), Value, Buffer))
1222 SmallString<256> FullPath;
1223 if (FS->IsRelativeOverlay) {
1224 FullPath = FS->getExternalContentsPrefixDir();
1225 assert(!FullPath.empty() &&
1226 "External contents prefix directory must exist");
1227 llvm::sys::path::append(FullPath, Value);
1232 if (FS->UseCanonicalizedPaths) {
1233 // Guarantee that old YAML files containing paths with ".." and "."
1234 // are properly canonicalized before read into the VFS.
1235 FullPath = sys::path::remove_leading_dotslash(FullPath);
1236 sys::path::remove_dots(FullPath, /*remove_dot_dot=*/true);
1238 ExternalContentsPath = FullPath.str();
1239 } else if (Key == "use-external-name") {
1241 if (!parseScalarBool(I->getValue(), Val))
1243 UseExternalName = Val ? RedirectingFileEntry::NK_External
1244 : RedirectingFileEntry::NK_Virtual;
1246 llvm_unreachable("key missing from Keys");
1250 if (Stream.failed())
1253 // check for missing keys
1255 error(N, "missing key 'contents' or 'external-contents'");
1258 if (!checkMissingKeys(N, Keys))
1261 // check invalid configuration
1262 if (Kind == EK_Directory &&
1263 UseExternalName != RedirectingFileEntry::NK_NotSet) {
1264 error(N, "'use-external-name' is not supported for directories");
1268 // Remove trailing slash(es), being careful not to remove the root path
1269 StringRef Trimmed(Name);
1270 size_t RootPathLen = sys::path::root_path(Trimmed).size();
1271 while (Trimmed.size() > RootPathLen &&
1272 sys::path::is_separator(Trimmed.back()))
1273 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
1274 // Get the last component
1275 StringRef LastComponent = sys::path::filename(Trimmed);
1277 std::unique_ptr<Entry> Result;
1280 Result = llvm::make_unique<RedirectingFileEntry>(
1281 LastComponent, std::move(ExternalContentsPath), UseExternalName);
1284 Result = llvm::make_unique<RedirectingDirectoryEntry>(
1285 LastComponent, std::move(EntryArrayContents),
1286 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1287 0, 0, 0, file_type::directory_file, sys::fs::all_all));
1291 StringRef Parent = sys::path::parent_path(Trimmed);
1295 // if 'name' contains multiple components, create implicit directory entries
1296 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
1297 E = sys::path::rend(Parent);
1299 std::vector<std::unique_ptr<Entry>> Entries;
1300 Entries.push_back(std::move(Result));
1301 Result = llvm::make_unique<RedirectingDirectoryEntry>(
1302 *I, std::move(Entries),
1303 Status("", getNextVirtualUniqueID(), std::chrono::system_clock::now(),
1304 0, 0, 0, file_type::directory_file, sys::fs::all_all));
1310 RedirectingFileSystemParser(yaml::Stream &S) : Stream(S) {}
1313 bool parse(yaml::Node *Root, RedirectingFileSystem *FS) {
1314 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
1316 error(Root, "expected mapping node");
1320 KeyStatusPair Fields[] = {
1321 KeyStatusPair("version", true),
1322 KeyStatusPair("case-sensitive", false),
1323 KeyStatusPair("use-external-names", false),
1324 KeyStatusPair("overlay-relative", false),
1325 KeyStatusPair("ignore-non-existent-contents", false),
1326 KeyStatusPair("roots", true),
1329 DenseMap<StringRef, KeyStatus> Keys(std::begin(Fields), std::end(Fields));
1330 std::vector<std::unique_ptr<Entry>> RootEntries;
1332 // Parse configuration and 'roots'
1333 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
1335 SmallString<10> KeyBuffer;
1337 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
1340 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
1343 if (Key == "roots") {
1344 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
1346 error(I->getValue(), "expected array");
1350 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
1352 if (std::unique_ptr<Entry> E = parseEntry(&*I, FS))
1353 RootEntries.push_back(std::move(E));
1357 } else if (Key == "version") {
1358 StringRef VersionString;
1359 SmallString<4> Storage;
1360 if (!parseScalarString(I->getValue(), VersionString, Storage))
1363 if (VersionString.getAsInteger<int>(10, Version)) {
1364 error(I->getValue(), "expected integer");
1368 error(I->getValue(), "invalid version number");
1372 error(I->getValue(), "version mismatch, expected 0");
1375 } else if (Key == "case-sensitive") {
1376 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
1378 } else if (Key == "overlay-relative") {
1379 if (!parseScalarBool(I->getValue(), FS->IsRelativeOverlay))
1381 } else if (Key == "use-external-names") {
1382 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
1384 } else if (Key == "ignore-non-existent-contents") {
1385 if (!parseScalarBool(I->getValue(), FS->IgnoreNonExistentContents))
1388 llvm_unreachable("key missing from Keys");
1392 if (Stream.failed())
1395 if (!checkMissingKeys(Top, Keys))
1398 // Now that we sucessefully parsed the YAML file, canonicalize the internal
1399 // representation to a proper directory tree so that we can search faster
1401 for (std::unique_ptr<Entry> &E : RootEntries)
1402 uniqueOverlayTree(FS, E.get());
1407 } // end of anonymous namespace
1409 Entry::~Entry() = default;
1411 RedirectingFileSystem *
1412 RedirectingFileSystem::create(std::unique_ptr<MemoryBuffer> Buffer,
1413 SourceMgr::DiagHandlerTy DiagHandler,
1414 StringRef YAMLFilePath, void *DiagContext,
1415 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1418 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
1420 SM.setDiagHandler(DiagHandler, DiagContext);
1421 yaml::document_iterator DI = Stream.begin();
1422 yaml::Node *Root = DI->getRoot();
1423 if (DI == Stream.end() || !Root) {
1424 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
1428 RedirectingFileSystemParser P(Stream);
1430 std::unique_ptr<RedirectingFileSystem> FS(
1431 new RedirectingFileSystem(std::move(ExternalFS)));
1433 if (!YAMLFilePath.empty()) {
1434 // Use the YAML path from -ivfsoverlay to compute the dir to be prefixed
1435 // to each 'external-contents' path.
1438 // -ivfsoverlay dummy.cache/vfs/vfs.yaml
1440 // FS->ExternalContentsPrefixDir => /<absolute_path_to>/dummy.cache/vfs
1442 SmallString<256> OverlayAbsDir = sys::path::parent_path(YAMLFilePath);
1443 std::error_code EC = llvm::sys::fs::make_absolute(OverlayAbsDir);
1444 assert(!EC && "Overlay dir final path must be absolute");
1446 FS->setExternalContentsPrefixDir(OverlayAbsDir);
1449 if (!P.parse(Root, FS.get()))
1452 return FS.release();
1455 ErrorOr<Entry *> RedirectingFileSystem::lookupPath(const Twine &Path_) {
1456 SmallString<256> Path;
1457 Path_.toVector(Path);
1459 // Handle relative paths
1460 if (std::error_code EC = makeAbsolute(Path))
1463 // Canonicalize path by removing ".", "..", "./", etc components. This is
1464 // a VFS request, do bot bother about symlinks in the path components
1465 // but canonicalize in order to perform the correct entry search.
1466 if (UseCanonicalizedPaths) {
1467 Path = sys::path::remove_leading_dotslash(Path);
1468 sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1472 return make_error_code(llvm::errc::invalid_argument);
1474 sys::path::const_iterator Start = sys::path::begin(Path);
1475 sys::path::const_iterator End = sys::path::end(Path);
1476 for (const std::unique_ptr<Entry> &Root : Roots) {
1477 ErrorOr<Entry *> Result = lookupPath(Start, End, Root.get());
1478 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
1481 return make_error_code(llvm::errc::no_such_file_or_directory);
1485 RedirectingFileSystem::lookupPath(sys::path::const_iterator Start,
1486 sys::path::const_iterator End, Entry *From) {
1487 #ifndef LLVM_ON_WIN32
1488 assert(!isTraversalComponent(*Start) &&
1489 !isTraversalComponent(From->getName()) &&
1490 "Paths should not contain traversal components");
1492 // FIXME: this is here to support windows, remove it once canonicalized
1493 // paths become globally default.
1494 if (Start->equals("."))
1498 StringRef FromName = From->getName();
1500 // Forward the search to the next component in case this is an empty one.
1501 if (!FromName.empty()) {
1502 if (CaseSensitive ? !Start->equals(FromName)
1503 : !Start->equals_lower(FromName))
1505 return make_error_code(llvm::errc::no_such_file_or_directory);
1515 auto *DE = dyn_cast<RedirectingDirectoryEntry>(From);
1517 return make_error_code(llvm::errc::not_a_directory);
1519 for (const std::unique_ptr<Entry> &DirEntry :
1520 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1521 ErrorOr<Entry *> Result = lookupPath(Start, End, DirEntry.get());
1522 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
1525 return make_error_code(llvm::errc::no_such_file_or_directory);
1528 static Status getRedirectedFileStatus(const Twine &Path, bool UseExternalNames,
1529 Status ExternalStatus) {
1530 Status S = ExternalStatus;
1531 if (!UseExternalNames)
1532 S = Status::copyWithNewName(S, Path.str());
1533 S.IsVFSMapped = true;
1537 ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path, Entry *E) {
1538 assert(E != nullptr);
1539 if (auto *F = dyn_cast<RedirectingFileEntry>(E)) {
1540 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
1541 assert(!S || S->getName() == F->getExternalContentsPath());
1543 return getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1546 } else { // directory
1547 auto *DE = cast<RedirectingDirectoryEntry>(E);
1548 return Status::copyWithNewName(DE->getStatus(), Path.str());
1552 ErrorOr<Status> RedirectingFileSystem::status(const Twine &Path) {
1553 ErrorOr<Entry *> Result = lookupPath(Path);
1555 return Result.getError();
1556 return status(Path, *Result);
1560 /// Provide a file wrapper with an overriden status.
1561 class FileWithFixedStatus : public File {
1562 std::unique_ptr<File> InnerFile;
1566 FileWithFixedStatus(std::unique_ptr<File> InnerFile, Status S)
1567 : InnerFile(std::move(InnerFile)), S(std::move(S)) {}
1569 ErrorOr<Status> status() override { return S; }
1570 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
1571 getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator,
1572 bool IsVolatile) override {
1573 return InnerFile->getBuffer(Name, FileSize, RequiresNullTerminator,
1576 std::error_code close() override { return InnerFile->close(); }
1578 } // end anonymous namespace
1580 ErrorOr<std::unique_ptr<File>>
1581 RedirectingFileSystem::openFileForRead(const Twine &Path) {
1582 ErrorOr<Entry *> E = lookupPath(Path);
1584 return E.getError();
1586 auto *F = dyn_cast<RedirectingFileEntry>(*E);
1587 if (!F) // FIXME: errc::not_a_file?
1588 return make_error_code(llvm::errc::invalid_argument);
1590 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
1594 auto ExternalStatus = (*Result)->status();
1595 if (!ExternalStatus)
1596 return ExternalStatus.getError();
1598 // FIXME: Update the status with the name and VFSMapped.
1599 Status S = getRedirectedFileStatus(Path, F->useExternalName(UseExternalNames),
1601 return std::unique_ptr<File>(
1602 llvm::make_unique<FileWithFixedStatus>(std::move(*Result), S));
1605 IntrusiveRefCntPtr<FileSystem>
1606 vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1607 SourceMgr::DiagHandlerTy DiagHandler,
1608 StringRef YAMLFilePath,
1610 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1611 return RedirectingFileSystem::create(std::move(Buffer), DiagHandler,
1612 YAMLFilePath, DiagContext,
1613 std::move(ExternalFS));
1616 static void getVFSEntries(Entry *SrcE, SmallVectorImpl<StringRef> &Path,
1617 SmallVectorImpl<YAMLVFSEntry> &Entries) {
1618 auto Kind = SrcE->getKind();
1619 if (Kind == EK_Directory) {
1620 auto *DE = dyn_cast<RedirectingDirectoryEntry>(SrcE);
1621 assert(DE && "Must be a directory");
1622 for (std::unique_ptr<Entry> &SubEntry :
1623 llvm::make_range(DE->contents_begin(), DE->contents_end())) {
1624 Path.push_back(SubEntry->getName());
1625 getVFSEntries(SubEntry.get(), Path, Entries);
1631 assert(Kind == EK_File && "Must be a EK_File");
1632 auto *FE = dyn_cast<RedirectingFileEntry>(SrcE);
1633 assert(FE && "Must be a file");
1634 SmallString<128> VPath;
1635 for (auto &Comp : Path)
1636 llvm::sys::path::append(VPath, Comp);
1637 Entries.push_back(YAMLVFSEntry(VPath.c_str(), FE->getExternalContentsPath()));
1640 void vfs::collectVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
1641 SourceMgr::DiagHandlerTy DiagHandler,
1642 StringRef YAMLFilePath,
1643 SmallVectorImpl<YAMLVFSEntry> &CollectedEntries,
1645 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
1646 RedirectingFileSystem *VFS = RedirectingFileSystem::create(
1647 std::move(Buffer), DiagHandler, YAMLFilePath, DiagContext,
1648 std::move(ExternalFS));
1649 ErrorOr<Entry *> RootE = VFS->lookupPath("/");
1652 SmallVector<StringRef, 8> Components;
1653 Components.push_back("/");
1654 getVFSEntries(*RootE, Components, CollectedEntries);
1657 UniqueID vfs::getNextVirtualUniqueID() {
1658 static std::atomic<unsigned> UID;
1659 unsigned ID = ++UID;
1660 // The following assumes that uint64_t max will never collide with a real
1661 // dev_t value from the OS.
1662 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1665 void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1666 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1667 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1668 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1669 Mappings.emplace_back(VirtualPath, RealPath);
1674 llvm::raw_ostream &OS;
1675 SmallVector<StringRef, 16> DirStack;
1676 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
1677 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1678 bool containedIn(StringRef Parent, StringRef Path);
1679 StringRef containedPart(StringRef Parent, StringRef Path);
1680 void startDirectory(StringRef Path);
1681 void endDirectory();
1682 void writeEntry(StringRef VPath, StringRef RPath);
1685 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
1686 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> UseExternalNames,
1687 Optional<bool> IsCaseSensitive, Optional<bool> IsOverlayRelative,
1688 Optional<bool> IgnoreNonExistentContents, StringRef OverlayDir);
1692 bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
1693 using namespace llvm::sys;
1694 // Compare each path component.
1695 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1696 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1697 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1698 if (*IParent != *IChild)
1701 // Have we exhausted the parent path?
1702 return IParent == EParent;
1705 StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1706 assert(!Parent.empty());
1707 assert(containedIn(Parent, Path));
1708 return Path.slice(Parent.size() + 1, StringRef::npos);
1711 void JSONWriter::startDirectory(StringRef Path) {
1713 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1714 DirStack.push_back(Path);
1715 unsigned Indent = getDirIndent();
1716 OS.indent(Indent) << "{\n";
1717 OS.indent(Indent + 2) << "'type': 'directory',\n";
1718 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1719 OS.indent(Indent + 2) << "'contents': [\n";
1722 void JSONWriter::endDirectory() {
1723 unsigned Indent = getDirIndent();
1724 OS.indent(Indent + 2) << "]\n";
1725 OS.indent(Indent) << "}";
1727 DirStack.pop_back();
1730 void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1731 unsigned Indent = getFileIndent();
1732 OS.indent(Indent) << "{\n";
1733 OS.indent(Indent + 2) << "'type': 'file',\n";
1734 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1735 OS.indent(Indent + 2) << "'external-contents': \""
1736 << llvm::yaml::escape(RPath) << "\"\n";
1737 OS.indent(Indent) << "}";
1740 void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
1741 Optional<bool> UseExternalNames,
1742 Optional<bool> IsCaseSensitive,
1743 Optional<bool> IsOverlayRelative,
1744 Optional<bool> IgnoreNonExistentContents,
1745 StringRef OverlayDir) {
1746 using namespace llvm::sys;
1750 if (IsCaseSensitive.hasValue())
1751 OS << " 'case-sensitive': '"
1752 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
1753 if (UseExternalNames.hasValue())
1754 OS << " 'use-external-names': '"
1755 << (UseExternalNames.getValue() ? "true" : "false") << "',\n";
1756 bool UseOverlayRelative = false;
1757 if (IsOverlayRelative.hasValue()) {
1758 UseOverlayRelative = IsOverlayRelative.getValue();
1759 OS << " 'overlay-relative': '"
1760 << (UseOverlayRelative ? "true" : "false") << "',\n";
1762 if (IgnoreNonExistentContents.hasValue())
1763 OS << " 'ignore-non-existent-contents': '"
1764 << (IgnoreNonExistentContents.getValue() ? "true" : "false") << "',\n";
1765 OS << " 'roots': [\n";
1767 if (!Entries.empty()) {
1768 const YAMLVFSEntry &Entry = Entries.front();
1769 startDirectory(path::parent_path(Entry.VPath));
1771 StringRef RPath = Entry.RPath;
1772 if (UseOverlayRelative) {
1773 unsigned OverlayDirLen = OverlayDir.size();
1774 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1775 "Overlay dir must be contained in RPath");
1776 RPath = RPath.slice(OverlayDirLen, RPath.size());
1779 writeEntry(path::filename(Entry.VPath), RPath);
1781 for (const auto &Entry : Entries.slice(1)) {
1782 StringRef Dir = path::parent_path(Entry.VPath);
1783 if (Dir == DirStack.back())
1786 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1791 startDirectory(Dir);
1793 StringRef RPath = Entry.RPath;
1794 if (UseOverlayRelative) {
1795 unsigned OverlayDirLen = OverlayDir.size();
1796 assert(RPath.substr(0, OverlayDirLen) == OverlayDir &&
1797 "Overlay dir must be contained in RPath");
1798 RPath = RPath.slice(OverlayDirLen, RPath.size());
1800 writeEntry(path::filename(Entry.VPath), RPath);
1803 while (!DirStack.empty()) {
1814 void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
1815 std::sort(Mappings.begin(), Mappings.end(),
1816 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
1817 return LHS.VPath < RHS.VPath;
1820 JSONWriter(OS).write(Mappings, UseExternalNames, IsCaseSensitive,
1821 IsOverlayRelative, IgnoreNonExistentContents,
1825 VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(
1826 const Twine &_Path, RedirectingFileSystem &FS,
1827 RedirectingDirectoryEntry::iterator Begin,
1828 RedirectingDirectoryEntry::iterator End, std::error_code &EC)
1829 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
1830 while (Current != End) {
1831 SmallString<128> PathStr(Dir);
1832 llvm::sys::path::append(PathStr, (*Current)->getName());
1833 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
1838 // Skip entries which do not map to a reliable external content.
1839 if (FS.ignoreNonExistentContents() &&
1840 S.getError() == llvm::errc::no_such_file_or_directory) {
1850 std::error_code VFSFromYamlDirIterImpl::increment() {
1851 assert(Current != End && "cannot iterate past end");
1852 while (++Current != End) {
1853 SmallString<128> PathStr(Dir);
1854 llvm::sys::path::append(PathStr, (*Current)->getName());
1855 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr);
1857 // Skip entries which do not map to a reliable external content.
1858 if (FS.ignoreNonExistentContents() &&
1859 S.getError() == llvm::errc::no_such_file_or_directory) {
1862 return S.getError();
1870 CurrentEntry = Status();
1871 return std::error_code();
1874 vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1876 std::error_code &EC)
1878 directory_iterator I = FS->dir_begin(Path, EC);
1879 if (I != directory_iterator()) {
1880 State = std::make_shared<IterState>();
1885 vfs::recursive_directory_iterator &
1886 recursive_directory_iterator::increment(std::error_code &EC) {
1887 assert(FS && State && !State->empty() && "incrementing past end");
1888 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1889 vfs::directory_iterator End;
1890 if (State->top()->isDirectory()) {
1891 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
1898 while (!State->empty() && State->top().increment(EC) == End)
1902 State.reset(); // end iterator