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 "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/ADT/StringSet.h"
17 #include "llvm/ADT/iterator_range.h"
18 #include "llvm/Support/Errc.h"
19 #include "llvm/Support/MemoryBuffer.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/YAMLParser.h"
25 using namespace clang;
26 using namespace clang::vfs;
28 using llvm::sys::fs::file_status;
29 using llvm::sys::fs::file_type;
30 using llvm::sys::fs::perms;
31 using llvm::sys::fs::UniqueID;
33 Status::Status(const file_status &Status)
34 : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()),
35 User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()),
36 Type(Status.type()), Perms(Status.permissions()), IsVFSMapped(false) {}
38 Status::Status(StringRef Name, StringRef ExternalName, UniqueID UID,
39 sys::TimeValue MTime, uint32_t User, uint32_t Group,
40 uint64_t Size, file_type Type, perms Perms)
41 : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size),
42 Type(Type), Perms(Perms), IsVFSMapped(false) {}
44 bool Status::equivalent(const Status &Other) const {
45 return getUniqueID() == Other.getUniqueID();
47 bool Status::isDirectory() const {
48 return Type == file_type::directory_file;
50 bool Status::isRegularFile() const {
51 return Type == file_type::regular_file;
53 bool Status::isOther() const {
54 return exists() && !isRegularFile() && !isDirectory() && !isSymlink();
56 bool Status::isSymlink() const {
57 return Type == file_type::symlink_file;
59 bool Status::isStatusKnown() const {
60 return Type != file_type::status_error;
62 bool Status::exists() const {
63 return isStatusKnown() && Type != file_type::file_not_found;
68 FileSystem::~FileSystem() {}
70 ErrorOr<std::unique_ptr<MemoryBuffer>>
71 FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize,
72 bool RequiresNullTerminator, bool IsVolatile) {
73 auto F = openFileForRead(Name);
77 return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile);
80 //===-----------------------------------------------------------------------===/
81 // RealFileSystem implementation
82 //===-----------------------------------------------------------------------===/
85 /// \brief Wrapper around a raw file descriptor.
86 class RealFile : public File {
89 friend class RealFileSystem;
90 RealFile(int FD) : FD(FD) {
91 assert(FD >= 0 && "Invalid or inactive file descriptor");
96 ErrorOr<Status> status() override;
97 ErrorOr<std::unique_ptr<MemoryBuffer>>
98 getBuffer(const Twine &Name, int64_t FileSize = -1,
99 bool RequiresNullTerminator = true,
100 bool IsVolatile = false) override;
101 std::error_code close() override;
102 void setName(StringRef Name) override;
104 } // end anonymous namespace
105 RealFile::~RealFile() { close(); }
107 ErrorOr<Status> RealFile::status() {
108 assert(FD != -1 && "cannot stat closed file");
109 if (!S.isStatusKnown()) {
110 file_status RealStatus;
111 if (std::error_code EC = sys::fs::status(FD, RealStatus))
113 Status NewS(RealStatus);
114 NewS.setName(S.getName());
120 ErrorOr<std::unique_ptr<MemoryBuffer>>
121 RealFile::getBuffer(const Twine &Name, int64_t FileSize,
122 bool RequiresNullTerminator, bool IsVolatile) {
123 assert(FD != -1 && "cannot get buffer for closed file");
124 return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator,
128 // FIXME: This is terrible, we need this for ::close.
129 #if !defined(_MSC_VER) && !defined(__MINGW32__)
135 #define S_ISFIFO(x) (0)
138 std::error_code RealFile::close() {
140 return std::error_code(errno, std::generic_category());
142 return std::error_code();
145 void RealFile::setName(StringRef Name) {
150 /// \brief The file system according to your operating system.
151 class RealFileSystem : public FileSystem {
153 ErrorOr<Status> status(const Twine &Path) override;
154 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
155 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
157 } // end anonymous namespace
159 ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
160 sys::fs::file_status RealStatus;
161 if (std::error_code EC = sys::fs::status(Path, RealStatus))
163 Status Result(RealStatus);
164 Result.setName(Path.str());
168 ErrorOr<std::unique_ptr<File>>
169 RealFileSystem::openFileForRead(const Twine &Name) {
171 if (std::error_code EC = sys::fs::openFileForRead(Name, FD))
173 std::unique_ptr<File> Result(new RealFile(FD));
174 Result->setName(Name.str());
175 return std::move(Result);
178 IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
179 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
184 class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
186 llvm::sys::fs::directory_iterator Iter;
188 RealFSDirIter(const Twine &_Path, std::error_code &EC)
189 : Path(_Path.str()), Iter(Path, EC) {
190 if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
191 llvm::sys::fs::file_status S;
192 EC = Iter->status(S);
194 CurrentEntry = Status(S);
195 CurrentEntry.setName(Iter->path());
200 std::error_code increment() override {
205 } else if (Iter == llvm::sys::fs::directory_iterator()) {
206 CurrentEntry = Status();
208 llvm::sys::fs::file_status S;
209 EC = Iter->status(S);
210 CurrentEntry = Status(S);
211 CurrentEntry.setName(Iter->path());
218 directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
219 std::error_code &EC) {
220 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
223 //===-----------------------------------------------------------------------===/
224 // OverlayFileSystem implementation
225 //===-----------------------------------------------------------------------===/
226 OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
230 void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
231 FSList.push_back(FS);
234 ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
235 // FIXME: handle symlinks that cross file systems
236 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
237 ErrorOr<Status> Status = (*I)->status(Path);
238 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
241 return make_error_code(llvm::errc::no_such_file_or_directory);
244 ErrorOr<std::unique_ptr<File>>
245 OverlayFileSystem::openFileForRead(const llvm::Twine &Path) {
246 // FIXME: handle symlinks that cross file systems
247 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
248 auto Result = (*I)->openFileForRead(Path);
249 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
252 return make_error_code(llvm::errc::no_such_file_or_directory);
255 clang::vfs::detail::DirIterImpl::~DirIterImpl() { }
258 class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
259 OverlayFileSystem &Overlays;
261 OverlayFileSystem::iterator CurrentFS;
262 directory_iterator CurrentDirIter;
263 llvm::StringSet<> SeenNames;
265 std::error_code incrementFS() {
266 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
268 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
270 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
271 if (EC && EC != errc::no_such_file_or_directory)
273 if (CurrentDirIter != directory_iterator())
276 return std::error_code();
279 std::error_code incrementDirIter(bool IsFirstTime) {
280 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
281 "incrementing past end");
284 CurrentDirIter.increment(EC);
285 if (!EC && CurrentDirIter == directory_iterator())
290 std::error_code incrementImpl(bool IsFirstTime) {
292 std::error_code EC = incrementDirIter(IsFirstTime);
293 if (EC || CurrentDirIter == directory_iterator()) {
294 CurrentEntry = Status();
297 CurrentEntry = *CurrentDirIter;
298 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
299 if (SeenNames.insert(Name).second)
300 return EC; // name not seen before
302 llvm_unreachable("returned above");
306 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
308 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
309 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
310 EC = incrementImpl(true);
313 std::error_code increment() override { return incrementImpl(false); }
315 } // end anonymous namespace
317 directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
318 std::error_code &EC) {
319 return directory_iterator(
320 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
323 //===-----------------------------------------------------------------------===/
324 // VFSFromYAML implementation
325 //===-----------------------------------------------------------------------===/
327 // Allow DenseMap<StringRef, ...>. This is useful below because we know all the
328 // strings are literals and will outlive the map, and there is no reason to
332 struct DenseMapInfo<StringRef> {
333 // This assumes that "" will never be a valid key.
334 static inline StringRef getEmptyKey() { return StringRef(""); }
335 static inline StringRef getTombstoneKey() { return StringRef(); }
336 static unsigned getHashValue(StringRef Val) { return HashString(Val); }
337 static bool isEqual(StringRef LHS, StringRef RHS) { return LHS == RHS; }
348 /// \brief A single file or directory in the VFS.
355 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
356 StringRef getName() const { return Name; }
357 EntryKind getKind() const { return Kind; }
360 class DirectoryEntry : public Entry {
361 std::vector<Entry *> Contents;
365 virtual ~DirectoryEntry();
366 DirectoryEntry(StringRef Name, std::vector<Entry *> Contents, Status S)
367 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
369 Status getStatus() { return S; }
370 typedef std::vector<Entry *>::iterator iterator;
371 iterator contents_begin() { return Contents.begin(); }
372 iterator contents_end() { return Contents.end(); }
373 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
376 class FileEntry : public Entry {
384 std::string ExternalContentsPath;
387 FileEntry(StringRef Name, StringRef ExternalContentsPath, NameKind UseName)
388 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
390 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
391 /// \brief whether to use the external path as the name for this file.
392 bool useExternalName(bool GlobalUseExternalName) const {
393 return UseName == NK_NotSet ? GlobalUseExternalName
394 : (UseName == NK_External);
396 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
401 class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
404 DirectoryEntry::iterator Current, End;
406 VFSFromYamlDirIterImpl(const Twine &Path, VFSFromYAML &FS,
407 DirectoryEntry::iterator Begin,
408 DirectoryEntry::iterator End, std::error_code &EC);
409 std::error_code increment() override;
412 /// \brief A virtual file system parsed from a YAML file.
414 /// Currently, this class allows creating virtual directories and mapping
415 /// virtual file paths to existing external files, available in \c ExternalFS.
417 /// The basic structure of the parsed file is:
420 /// 'version': <version number>,
421 /// <optional configuration>
423 /// <directory entries>
428 /// All configuration options are optional.
429 /// 'case-sensitive': <boolean, default=true>
430 /// 'use-external-names': <boolean, default=true>
432 /// Virtual directories are represented as
435 /// 'type': 'directory',
436 /// 'name': <string>,
437 /// 'contents': [ <file or directory entries> ]
441 /// The default attributes for virtual directories are:
443 /// MTime = now() when created
447 /// UniqueID = unspecified unique value
450 /// Re-mapped files are represented as
454 /// 'name': <string>,
455 /// 'use-external-name': <boolean> # Optional
456 /// 'external-contents': <path to external file>)
460 /// and inherit their attributes from the external contents.
462 /// In both cases, the 'name' field may contain multiple path components (e.g.
463 /// /path/to/file). However, any directory that contains more than one child
464 /// must be uniquely represented by a directory entry.
465 class VFSFromYAML : public vfs::FileSystem {
466 std::vector<Entry *> Roots; ///< The root(s) of the virtual file system.
467 /// \brief The file system to use for external references.
468 IntrusiveRefCntPtr<FileSystem> ExternalFS;
470 /// @name Configuration
473 /// \brief Whether to perform case-sensitive comparisons.
475 /// Currently, case-insensitive matching only works correctly with ASCII.
478 /// \brief Whether to use to use the value of 'external-contents' for the
479 /// names of files. This global value is overridable on a per-file basis.
480 bool UseExternalNames;
483 friend class VFSFromYAMLParser;
486 VFSFromYAML(IntrusiveRefCntPtr<FileSystem> ExternalFS)
487 : ExternalFS(ExternalFS), CaseSensitive(true), UseExternalNames(true) {}
489 /// \brief Looks up \p Path in \c Roots.
490 ErrorOr<Entry *> lookupPath(const Twine &Path);
492 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
493 /// recursing into the contents of \p From if it is a directory.
494 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
495 sys::path::const_iterator End, Entry *From);
497 /// \brief Get the status of a given an \c Entry.
498 ErrorOr<Status> status(const Twine &Path, Entry *E);
503 /// \brief Parses \p Buffer, which is expected to be in YAML format and
504 /// returns a virtual file system representing its contents.
505 static VFSFromYAML *create(std::unique_ptr<MemoryBuffer> Buffer,
506 SourceMgr::DiagHandlerTy DiagHandler,
508 IntrusiveRefCntPtr<FileSystem> ExternalFS);
510 ErrorOr<Status> status(const Twine &Path) override;
511 ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override;
513 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
514 ErrorOr<Entry *> E = lookupPath(Dir);
517 return directory_iterator();
519 ErrorOr<Status> S = status(Dir, *E);
522 return directory_iterator();
524 if (!S->isDirectory()) {
525 EC = std::error_code(static_cast<int>(errc::not_a_directory),
526 std::system_category());
527 return directory_iterator();
530 DirectoryEntry *D = cast<DirectoryEntry>(*E);
531 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
532 *this, D->contents_begin(), D->contents_end(), EC));
536 /// \brief A helper class to hold the common YAML parsing state.
537 class VFSFromYAMLParser {
538 yaml::Stream &Stream;
540 void error(yaml::Node *N, const Twine &Msg) {
541 Stream.printError(N, Msg);
545 bool parseScalarString(yaml::Node *N, StringRef &Result,
546 SmallVectorImpl<char> &Storage) {
547 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
549 error(N, "expected string");
552 Result = S->getValue(Storage);
557 bool parseScalarBool(yaml::Node *N, bool &Result) {
558 SmallString<5> Storage;
560 if (!parseScalarString(N, Value, Storage))
563 if (Value.equals_lower("true") || Value.equals_lower("on") ||
564 Value.equals_lower("yes") || Value == "1") {
567 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
568 Value.equals_lower("no") || Value == "0") {
573 error(N, "expected boolean value");
578 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
582 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
585 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
586 DenseMap<StringRef, KeyStatus> &Keys) {
587 if (!Keys.count(Key)) {
588 error(KeyNode, "unknown key");
591 KeyStatus &S = Keys[Key];
593 error(KeyNode, Twine("duplicate key '") + Key + "'");
601 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
602 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
605 if (I->second.Required && !I->second.Seen) {
606 error(Obj, Twine("missing key '") + I->first + "'");
613 Entry *parseEntry(yaml::Node *N) {
614 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
616 error(N, "expected mapping node for file or directory entry");
620 KeyStatusPair Fields[] = {
621 KeyStatusPair("name", true),
622 KeyStatusPair("type", true),
623 KeyStatusPair("contents", false),
624 KeyStatusPair("external-contents", false),
625 KeyStatusPair("use-external-name", false),
628 DenseMap<StringRef, KeyStatus> Keys(
629 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
631 bool HasContents = false; // external or otherwise
632 std::vector<Entry *> EntryArrayContents;
633 std::string ExternalContentsPath;
635 FileEntry::NameKind UseExternalName = FileEntry::NK_NotSet;
638 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
641 // Reuse the buffer for key and value, since we don't look at key after
643 SmallString<256> Buffer;
644 if (!parseScalarString(I->getKey(), Key, Buffer))
647 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
652 if (!parseScalarString(I->getValue(), Value, Buffer))
655 } else if (Key == "type") {
656 if (!parseScalarString(I->getValue(), Value, Buffer))
660 else if (Value == "directory")
663 error(I->getValue(), "unknown value for 'type'");
666 } else if (Key == "contents") {
669 "entry already has 'contents' or 'external-contents'");
673 yaml::SequenceNode *Contents =
674 dyn_cast<yaml::SequenceNode>(I->getValue());
676 // FIXME: this is only for directories, what about files?
677 error(I->getValue(), "expected array");
681 for (yaml::SequenceNode::iterator I = Contents->begin(),
684 if (Entry *E = parseEntry(&*I))
685 EntryArrayContents.push_back(E);
689 } else if (Key == "external-contents") {
692 "entry already has 'contents' or 'external-contents'");
696 if (!parseScalarString(I->getValue(), Value, Buffer))
698 ExternalContentsPath = Value;
699 } else if (Key == "use-external-name") {
701 if (!parseScalarBool(I->getValue(), Val))
703 UseExternalName = Val ? FileEntry::NK_External : FileEntry::NK_Virtual;
705 llvm_unreachable("key missing from Keys");
712 // check for missing keys
714 error(N, "missing key 'contents' or 'external-contents'");
717 if (!checkMissingKeys(N, Keys))
720 // check invalid configuration
721 if (Kind == EK_Directory && UseExternalName != FileEntry::NK_NotSet) {
722 error(N, "'use-external-name' is not supported for directories");
726 // Remove trailing slash(es), being careful not to remove the root path
727 StringRef Trimmed(Name);
728 size_t RootPathLen = sys::path::root_path(Trimmed).size();
729 while (Trimmed.size() > RootPathLen &&
730 sys::path::is_separator(Trimmed.back()))
731 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
732 // Get the last component
733 StringRef LastComponent = sys::path::filename(Trimmed);
735 Entry *Result = nullptr;
738 Result = new FileEntry(LastComponent, std::move(ExternalContentsPath),
742 Result = new DirectoryEntry(LastComponent, std::move(EntryArrayContents),
743 Status("", "", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0,
744 0, file_type::directory_file, sys::fs::all_all));
748 StringRef Parent = sys::path::parent_path(Trimmed);
752 // if 'name' contains multiple components, create implicit directory entries
753 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
754 E = sys::path::rend(Parent);
756 Result = new DirectoryEntry(*I, llvm::makeArrayRef(Result),
757 Status("", "", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0,
758 0, file_type::directory_file, sys::fs::all_all));
764 VFSFromYAMLParser(yaml::Stream &S) : Stream(S) {}
767 bool parse(yaml::Node *Root, VFSFromYAML *FS) {
768 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
770 error(Root, "expected mapping node");
774 KeyStatusPair Fields[] = {
775 KeyStatusPair("version", true),
776 KeyStatusPair("case-sensitive", false),
777 KeyStatusPair("use-external-names", false),
778 KeyStatusPair("roots", true),
781 DenseMap<StringRef, KeyStatus> Keys(
782 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
784 // Parse configuration and 'roots'
785 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
787 SmallString<10> KeyBuffer;
789 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
792 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
795 if (Key == "roots") {
796 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
798 error(I->getValue(), "expected array");
802 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
804 if (Entry *E = parseEntry(&*I))
805 FS->Roots.push_back(E);
809 } else if (Key == "version") {
810 StringRef VersionString;
811 SmallString<4> Storage;
812 if (!parseScalarString(I->getValue(), VersionString, Storage))
815 if (VersionString.getAsInteger<int>(10, Version)) {
816 error(I->getValue(), "expected integer");
820 error(I->getValue(), "invalid version number");
824 error(I->getValue(), "version mismatch, expected 0");
827 } else if (Key == "case-sensitive") {
828 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
830 } else if (Key == "use-external-names") {
831 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
834 llvm_unreachable("key missing from Keys");
841 if (!checkMissingKeys(Top, Keys))
846 } // end of anonymous namespace
849 DirectoryEntry::~DirectoryEntry() { llvm::DeleteContainerPointers(Contents); }
851 VFSFromYAML::~VFSFromYAML() { llvm::DeleteContainerPointers(Roots); }
853 VFSFromYAML *VFSFromYAML::create(std::unique_ptr<MemoryBuffer> Buffer,
854 SourceMgr::DiagHandlerTy DiagHandler,
856 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
859 yaml::Stream Stream(Buffer->getMemBufferRef(), SM);
861 SM.setDiagHandler(DiagHandler, DiagContext);
862 yaml::document_iterator DI = Stream.begin();
863 yaml::Node *Root = DI->getRoot();
864 if (DI == Stream.end() || !Root) {
865 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
869 VFSFromYAMLParser P(Stream);
871 std::unique_ptr<VFSFromYAML> FS(new VFSFromYAML(ExternalFS));
872 if (!P.parse(Root, FS.get()))
878 ErrorOr<Entry *> VFSFromYAML::lookupPath(const Twine &Path_) {
879 SmallString<256> Path;
880 Path_.toVector(Path);
882 // Handle relative paths
883 if (std::error_code EC = sys::fs::make_absolute(Path))
887 return make_error_code(llvm::errc::invalid_argument);
889 sys::path::const_iterator Start = sys::path::begin(Path);
890 sys::path::const_iterator End = sys::path::end(Path);
891 for (std::vector<Entry *>::iterator I = Roots.begin(), E = Roots.end();
893 ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
894 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
897 return make_error_code(llvm::errc::no_such_file_or_directory);
900 ErrorOr<Entry *> VFSFromYAML::lookupPath(sys::path::const_iterator Start,
901 sys::path::const_iterator End,
903 if (Start->equals("."))
907 if (CaseSensitive ? !Start->equals(From->getName())
908 : !Start->equals_lower(From->getName()))
910 return make_error_code(llvm::errc::no_such_file_or_directory);
919 DirectoryEntry *DE = dyn_cast<DirectoryEntry>(From);
921 return make_error_code(llvm::errc::not_a_directory);
923 for (DirectoryEntry::iterator I = DE->contents_begin(),
924 E = DE->contents_end();
926 ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
927 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
930 return make_error_code(llvm::errc::no_such_file_or_directory);
933 ErrorOr<Status> VFSFromYAML::status(const Twine &Path, Entry *E) {
934 assert(E != nullptr);
935 std::string PathStr(Path.str());
936 if (FileEntry *F = dyn_cast<FileEntry>(E)) {
937 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
938 assert(!S || S->getName() == F->getExternalContentsPath());
939 if (S && !F->useExternalName(UseExternalNames))
942 S->IsVFSMapped = true;
944 } else { // directory
945 DirectoryEntry *DE = cast<DirectoryEntry>(E);
946 Status S = DE->getStatus();
952 ErrorOr<Status> VFSFromYAML::status(const Twine &Path) {
953 ErrorOr<Entry *> Result = lookupPath(Path);
955 return Result.getError();
956 return status(Path, *Result);
959 ErrorOr<std::unique_ptr<File>> VFSFromYAML::openFileForRead(const Twine &Path) {
960 ErrorOr<Entry *> E = lookupPath(Path);
964 FileEntry *F = dyn_cast<FileEntry>(*E);
965 if (!F) // FIXME: errc::not_a_file?
966 return make_error_code(llvm::errc::invalid_argument);
968 auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath());
972 if (!F->useExternalName(UseExternalNames))
973 (*Result)->setName(Path.str());
978 IntrusiveRefCntPtr<FileSystem>
979 vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer,
980 SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext,
981 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
982 return VFSFromYAML::create(std::move(Buffer), DiagHandler, DiagContext,
986 UniqueID vfs::getNextVirtualUniqueID() {
987 static std::atomic<unsigned> UID;
989 // The following assumes that uint64_t max will never collide with a real
990 // dev_t value from the OS.
991 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
995 static bool pathHasTraversal(StringRef Path) {
996 using namespace llvm::sys;
997 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
998 if (Comp == "." || Comp == "..")
1004 void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1005 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1006 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1007 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1008 Mappings.emplace_back(VirtualPath, RealPath);
1013 llvm::raw_ostream &OS;
1014 SmallVector<StringRef, 16> DirStack;
1015 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
1016 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1017 bool containedIn(StringRef Parent, StringRef Path);
1018 StringRef containedPart(StringRef Parent, StringRef Path);
1019 void startDirectory(StringRef Path);
1020 void endDirectory();
1021 void writeEntry(StringRef VPath, StringRef RPath);
1024 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
1025 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> IsCaseSensitive);
1029 bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
1030 using namespace llvm::sys;
1031 // Compare each path component.
1032 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1033 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1034 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1035 if (*IParent != *IChild)
1038 // Have we exhausted the parent path?
1039 return IParent == EParent;
1042 StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1043 assert(!Parent.empty());
1044 assert(containedIn(Parent, Path));
1045 return Path.slice(Parent.size() + 1, StringRef::npos);
1048 void JSONWriter::startDirectory(StringRef Path) {
1050 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1051 DirStack.push_back(Path);
1052 unsigned Indent = getDirIndent();
1053 OS.indent(Indent) << "{\n";
1054 OS.indent(Indent + 2) << "'type': 'directory',\n";
1055 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1056 OS.indent(Indent + 2) << "'contents': [\n";
1059 void JSONWriter::endDirectory() {
1060 unsigned Indent = getDirIndent();
1061 OS.indent(Indent + 2) << "]\n";
1062 OS.indent(Indent) << "}";
1064 DirStack.pop_back();
1067 void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1068 unsigned Indent = getFileIndent();
1069 OS.indent(Indent) << "{\n";
1070 OS.indent(Indent + 2) << "'type': 'file',\n";
1071 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1072 OS.indent(Indent + 2) << "'external-contents': \""
1073 << llvm::yaml::escape(RPath) << "\"\n";
1074 OS.indent(Indent) << "}";
1077 void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
1078 Optional<bool> IsCaseSensitive) {
1079 using namespace llvm::sys;
1083 if (IsCaseSensitive.hasValue())
1084 OS << " 'case-sensitive': '"
1085 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
1086 OS << " 'roots': [\n";
1088 if (!Entries.empty()) {
1089 const YAMLVFSEntry &Entry = Entries.front();
1090 startDirectory(path::parent_path(Entry.VPath));
1091 writeEntry(path::filename(Entry.VPath), Entry.RPath);
1093 for (const auto &Entry : Entries.slice(1)) {
1094 StringRef Dir = path::parent_path(Entry.VPath);
1095 if (Dir == DirStack.back())
1098 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1103 startDirectory(Dir);
1105 writeEntry(path::filename(Entry.VPath), Entry.RPath);
1108 while (!DirStack.empty()) {
1119 void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
1120 std::sort(Mappings.begin(), Mappings.end(),
1121 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
1122 return LHS.VPath < RHS.VPath;
1125 JSONWriter(OS).write(Mappings, IsCaseSensitive);
1128 VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(const Twine &_Path,
1130 DirectoryEntry::iterator Begin,
1131 DirectoryEntry::iterator End,
1132 std::error_code &EC)
1133 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
1134 if (Current != End) {
1135 SmallString<128> PathStr(Dir);
1136 llvm::sys::path::append(PathStr, (*Current)->getName());
1137 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr.str());
1145 std::error_code VFSFromYamlDirIterImpl::increment() {
1146 assert(Current != End && "cannot iterate past end");
1147 if (++Current != End) {
1148 SmallString<128> PathStr(Dir);
1149 llvm::sys::path::append(PathStr, (*Current)->getName());
1150 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr.str());
1152 return S.getError();
1155 CurrentEntry = Status();
1157 return std::error_code();
1160 vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1162 std::error_code &EC)
1164 directory_iterator I = FS->dir_begin(Path, EC);
1165 if (!EC && I != directory_iterator()) {
1166 State = std::make_shared<IterState>();
1171 vfs::recursive_directory_iterator &
1172 recursive_directory_iterator::increment(std::error_code &EC) {
1173 assert(FS && State && !State->empty() && "incrementing past end");
1174 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1175 vfs::directory_iterator End;
1176 if (State->top()->isDirectory()) {
1177 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
1186 while (!State->empty() && State->top().increment(EC) == End)
1190 State.reset(); // end iterator