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/iterator_range.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/StringSet.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 std::error_code FileSystem::getBufferForFile(
71 const llvm::Twine &Name, std::unique_ptr<MemoryBuffer> &Result,
72 int64_t FileSize, bool RequiresNullTerminator, bool IsVolatile) {
73 std::unique_ptr<File> F;
74 if (std::error_code EC = openFileForRead(Name, F))
78 F->getBuffer(Name, Result, FileSize, RequiresNullTerminator, IsVolatile);
82 //===-----------------------------------------------------------------------===/
83 // RealFileSystem implementation
84 //===-----------------------------------------------------------------------===/
87 /// \brief Wrapper around a raw file descriptor.
88 class RealFile : public File {
91 friend class RealFileSystem;
92 RealFile(int FD) : FD(FD) {
93 assert(FD >= 0 && "Invalid or inactive file descriptor");
98 ErrorOr<Status> status() override;
99 std::error_code getBuffer(const Twine &Name,
100 std::unique_ptr<MemoryBuffer> &Result,
101 int64_t FileSize = -1,
102 bool RequiresNullTerminator = true,
103 bool IsVolatile = false) override;
104 std::error_code close() override;
105 void setName(StringRef Name) override;
107 } // end anonymous namespace
108 RealFile::~RealFile() { close(); }
110 ErrorOr<Status> RealFile::status() {
111 assert(FD != -1 && "cannot stat closed file");
112 if (!S.isStatusKnown()) {
113 file_status RealStatus;
114 if (std::error_code EC = sys::fs::status(FD, RealStatus))
116 Status NewS(RealStatus);
117 NewS.setName(S.getName());
123 std::error_code RealFile::getBuffer(const Twine &Name,
124 std::unique_ptr<MemoryBuffer> &Result,
126 bool RequiresNullTerminator,
128 assert(FD != -1 && "cannot get buffer for closed file");
129 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
130 MemoryBuffer::getOpenFile(FD, Name.str().c_str(), FileSize,
131 RequiresNullTerminator, IsVolatile);
132 if (std::error_code EC = BufferOrErr.getError())
134 Result = std::move(BufferOrErr.get());
135 return std::error_code();
138 // FIXME: This is terrible, we need this for ::close.
139 #if !defined(_MSC_VER) && !defined(__MINGW32__)
145 #define S_ISFIFO(x) (0)
148 std::error_code RealFile::close() {
150 return std::error_code(errno, std::generic_category());
152 return std::error_code();
155 void RealFile::setName(StringRef Name) {
160 /// \brief The file system according to your operating system.
161 class RealFileSystem : public FileSystem {
163 ErrorOr<Status> status(const Twine &Path) override;
164 std::error_code openFileForRead(const Twine &Path,
165 std::unique_ptr<File> &Result) override;
166 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override;
168 } // end anonymous namespace
170 ErrorOr<Status> RealFileSystem::status(const Twine &Path) {
171 sys::fs::file_status RealStatus;
172 if (std::error_code EC = sys::fs::status(Path, RealStatus))
174 Status Result(RealStatus);
175 Result.setName(Path.str());
179 std::error_code RealFileSystem::openFileForRead(const Twine &Name,
180 std::unique_ptr<File> &Result) {
182 if (std::error_code EC = sys::fs::openFileForRead(Name, FD))
184 Result.reset(new RealFile(FD));
185 Result->setName(Name.str());
186 return std::error_code();
189 IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() {
190 static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem();
195 class RealFSDirIter : public clang::vfs::detail::DirIterImpl {
197 llvm::sys::fs::directory_iterator Iter;
199 RealFSDirIter(const Twine &_Path, std::error_code &EC)
200 : Path(_Path.str()), Iter(Path, EC) {
201 if (!EC && Iter != llvm::sys::fs::directory_iterator()) {
202 llvm::sys::fs::file_status S;
203 EC = Iter->status(S);
205 CurrentEntry = Status(S);
206 CurrentEntry.setName(Iter->path());
211 std::error_code increment() override {
216 } else if (Iter == llvm::sys::fs::directory_iterator()) {
217 CurrentEntry = Status();
219 llvm::sys::fs::file_status S;
220 EC = Iter->status(S);
221 CurrentEntry = Status(S);
222 CurrentEntry.setName(Iter->path());
229 directory_iterator RealFileSystem::dir_begin(const Twine &Dir,
230 std::error_code &EC) {
231 return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC));
234 //===-----------------------------------------------------------------------===/
235 // OverlayFileSystem implementation
236 //===-----------------------------------------------------------------------===/
237 OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) {
241 void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) {
242 FSList.push_back(FS);
245 ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) {
246 // FIXME: handle symlinks that cross file systems
247 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
248 ErrorOr<Status> Status = (*I)->status(Path);
249 if (Status || Status.getError() != llvm::errc::no_such_file_or_directory)
252 return make_error_code(llvm::errc::no_such_file_or_directory);
256 OverlayFileSystem::openFileForRead(const llvm::Twine &Path,
257 std::unique_ptr<File> &Result) {
258 // FIXME: handle symlinks that cross file systems
259 for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) {
260 std::error_code EC = (*I)->openFileForRead(Path, Result);
261 if (!EC || EC != llvm::errc::no_such_file_or_directory)
264 return make_error_code(llvm::errc::no_such_file_or_directory);
267 clang::vfs::detail::DirIterImpl::~DirIterImpl() { }
270 class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl {
271 OverlayFileSystem &Overlays;
273 OverlayFileSystem::iterator CurrentFS;
274 directory_iterator CurrentDirIter;
275 llvm::StringSet<> SeenNames;
277 std::error_code incrementFS() {
278 assert(CurrentFS != Overlays.overlays_end() && "incrementing past end");
280 for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) {
282 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
283 if (EC && EC != errc::no_such_file_or_directory)
285 if (CurrentDirIter != directory_iterator())
288 return std::error_code();
291 std::error_code incrementDirIter(bool IsFirstTime) {
292 assert((IsFirstTime || CurrentDirIter != directory_iterator()) &&
293 "incrementing past end");
296 CurrentDirIter.increment(EC);
297 if (!EC && CurrentDirIter == directory_iterator())
302 std::error_code incrementImpl(bool IsFirstTime) {
304 std::error_code EC = incrementDirIter(IsFirstTime);
305 if (EC || CurrentDirIter == directory_iterator()) {
306 CurrentEntry = Status();
309 CurrentEntry = *CurrentDirIter;
310 StringRef Name = llvm::sys::path::filename(CurrentEntry.getName());
311 if (SeenNames.insert(Name))
312 return EC; // name not seen before
314 llvm_unreachable("returned above");
318 OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS,
320 : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) {
321 CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC);
322 EC = incrementImpl(true);
325 std::error_code increment() override { return incrementImpl(false); }
327 } // end anonymous namespace
329 directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir,
330 std::error_code &EC) {
331 return directory_iterator(
332 std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC));
335 //===-----------------------------------------------------------------------===/
336 // VFSFromYAML implementation
337 //===-----------------------------------------------------------------------===/
339 // Allow DenseMap<StringRef, ...>. This is useful below because we know all the
340 // strings are literals and will outlive the map, and there is no reason to
344 struct DenseMapInfo<StringRef> {
345 // This assumes that "" will never be a valid key.
346 static inline StringRef getEmptyKey() { return StringRef(""); }
347 static inline StringRef getTombstoneKey() { return StringRef(); }
348 static unsigned getHashValue(StringRef Val) { return HashString(Val); }
349 static bool isEqual(StringRef LHS, StringRef RHS) { return LHS == RHS; }
360 /// \brief A single file or directory in the VFS.
367 Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {}
368 StringRef getName() const { return Name; }
369 EntryKind getKind() const { return Kind; }
372 class DirectoryEntry : public Entry {
373 std::vector<Entry *> Contents;
377 virtual ~DirectoryEntry();
378 DirectoryEntry(StringRef Name, std::vector<Entry *> Contents, Status S)
379 : Entry(EK_Directory, Name), Contents(std::move(Contents)),
381 Status getStatus() { return S; }
382 typedef std::vector<Entry *>::iterator iterator;
383 iterator contents_begin() { return Contents.begin(); }
384 iterator contents_end() { return Contents.end(); }
385 static bool classof(const Entry *E) { return E->getKind() == EK_Directory; }
388 class FileEntry : public Entry {
396 std::string ExternalContentsPath;
399 FileEntry(StringRef Name, StringRef ExternalContentsPath, NameKind UseName)
400 : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath),
402 StringRef getExternalContentsPath() const { return ExternalContentsPath; }
403 /// \brief whether to use the external path as the name for this file.
404 bool useExternalName(bool GlobalUseExternalName) const {
405 return UseName == NK_NotSet ? GlobalUseExternalName
406 : (UseName == NK_External);
408 static bool classof(const Entry *E) { return E->getKind() == EK_File; }
413 class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl {
416 DirectoryEntry::iterator Current, End;
418 VFSFromYamlDirIterImpl(const Twine &Path, VFSFromYAML &FS,
419 DirectoryEntry::iterator Begin,
420 DirectoryEntry::iterator End, std::error_code &EC);
421 std::error_code increment() override;
424 /// \brief A virtual file system parsed from a YAML file.
426 /// Currently, this class allows creating virtual directories and mapping
427 /// virtual file paths to existing external files, available in \c ExternalFS.
429 /// The basic structure of the parsed file is:
432 /// 'version': <version number>,
433 /// <optional configuration>
435 /// <directory entries>
440 /// All configuration options are optional.
441 /// 'case-sensitive': <boolean, default=true>
442 /// 'use-external-names': <boolean, default=true>
444 /// Virtual directories are represented as
447 /// 'type': 'directory',
448 /// 'name': <string>,
449 /// 'contents': [ <file or directory entries> ]
453 /// The default attributes for virtual directories are:
455 /// MTime = now() when created
459 /// UniqueID = unspecified unique value
462 /// Re-mapped files are represented as
466 /// 'name': <string>,
467 /// 'use-external-name': <boolean> # Optional
468 /// 'external-contents': <path to external file>)
472 /// and inherit their attributes from the external contents.
474 /// In both cases, the 'name' field may contain multiple path components (e.g.
475 /// /path/to/file). However, any directory that contains more than one child
476 /// must be uniquely represented by a directory entry.
477 class VFSFromYAML : public vfs::FileSystem {
478 std::vector<Entry *> Roots; ///< The root(s) of the virtual file system.
479 /// \brief The file system to use for external references.
480 IntrusiveRefCntPtr<FileSystem> ExternalFS;
482 /// @name Configuration
485 /// \brief Whether to perform case-sensitive comparisons.
487 /// Currently, case-insensitive matching only works correctly with ASCII.
490 /// \brief Whether to use to use the value of 'external-contents' for the
491 /// names of files. This global value is overridable on a per-file basis.
492 bool UseExternalNames;
495 friend class VFSFromYAMLParser;
498 VFSFromYAML(IntrusiveRefCntPtr<FileSystem> ExternalFS)
499 : ExternalFS(ExternalFS), CaseSensitive(true), UseExternalNames(true) {}
501 /// \brief Looks up \p Path in \c Roots.
502 ErrorOr<Entry *> lookupPath(const Twine &Path);
504 /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly
505 /// recursing into the contents of \p From if it is a directory.
506 ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start,
507 sys::path::const_iterator End, Entry *From);
509 /// \brief Get the status of a given an \c Entry.
510 ErrorOr<Status> status(const Twine &Path, Entry *E);
515 /// \brief Parses \p Buffer, which is expected to be in YAML format and
516 /// returns a virtual file system representing its contents.
518 /// Takes ownership of \p Buffer.
519 static VFSFromYAML *create(MemoryBuffer *Buffer,
520 SourceMgr::DiagHandlerTy DiagHandler,
522 IntrusiveRefCntPtr<FileSystem> ExternalFS);
524 ErrorOr<Status> status(const Twine &Path) override;
525 std::error_code openFileForRead(const Twine &Path,
526 std::unique_ptr<File> &Result) override;
528 directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{
529 ErrorOr<Entry *> E = lookupPath(Dir);
532 return directory_iterator();
534 ErrorOr<Status> S = status(Dir, *E);
537 return directory_iterator();
539 if (!S->isDirectory()) {
540 EC = std::error_code(static_cast<int>(errc::not_a_directory),
541 std::system_category());
542 return directory_iterator();
545 DirectoryEntry *D = cast<DirectoryEntry>(*E);
546 return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir,
547 *this, D->contents_begin(), D->contents_end(), EC));
551 /// \brief A helper class to hold the common YAML parsing state.
552 class VFSFromYAMLParser {
553 yaml::Stream &Stream;
555 void error(yaml::Node *N, const Twine &Msg) {
556 Stream.printError(N, Msg);
560 bool parseScalarString(yaml::Node *N, StringRef &Result,
561 SmallVectorImpl<char> &Storage) {
562 yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N);
564 error(N, "expected string");
567 Result = S->getValue(Storage);
572 bool parseScalarBool(yaml::Node *N, bool &Result) {
573 SmallString<5> Storage;
575 if (!parseScalarString(N, Value, Storage))
578 if (Value.equals_lower("true") || Value.equals_lower("on") ||
579 Value.equals_lower("yes") || Value == "1") {
582 } else if (Value.equals_lower("false") || Value.equals_lower("off") ||
583 Value.equals_lower("no") || Value == "0") {
588 error(N, "expected boolean value");
593 KeyStatus(bool Required=false) : Required(Required), Seen(false) {}
597 typedef std::pair<StringRef, KeyStatus> KeyStatusPair;
600 bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key,
601 DenseMap<StringRef, KeyStatus> &Keys) {
602 if (!Keys.count(Key)) {
603 error(KeyNode, "unknown key");
606 KeyStatus &S = Keys[Key];
608 error(KeyNode, Twine("duplicate key '") + Key + "'");
616 bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) {
617 for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(),
620 if (I->second.Required && !I->second.Seen) {
621 error(Obj, Twine("missing key '") + I->first + "'");
628 Entry *parseEntry(yaml::Node *N) {
629 yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N);
631 error(N, "expected mapping node for file or directory entry");
635 KeyStatusPair Fields[] = {
636 KeyStatusPair("name", true),
637 KeyStatusPair("type", true),
638 KeyStatusPair("contents", false),
639 KeyStatusPair("external-contents", false),
640 KeyStatusPair("use-external-name", false),
643 DenseMap<StringRef, KeyStatus> Keys(
644 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
646 bool HasContents = false; // external or otherwise
647 std::vector<Entry *> EntryArrayContents;
648 std::string ExternalContentsPath;
650 FileEntry::NameKind UseExternalName = FileEntry::NK_NotSet;
653 for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E;
656 // Reuse the buffer for key and value, since we don't look at key after
658 SmallString<256> Buffer;
659 if (!parseScalarString(I->getKey(), Key, Buffer))
662 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
667 if (!parseScalarString(I->getValue(), Value, Buffer))
670 } else if (Key == "type") {
671 if (!parseScalarString(I->getValue(), Value, Buffer))
675 else if (Value == "directory")
678 error(I->getValue(), "unknown value for 'type'");
681 } else if (Key == "contents") {
684 "entry already has 'contents' or 'external-contents'");
688 yaml::SequenceNode *Contents =
689 dyn_cast<yaml::SequenceNode>(I->getValue());
691 // FIXME: this is only for directories, what about files?
692 error(I->getValue(), "expected array");
696 for (yaml::SequenceNode::iterator I = Contents->begin(),
699 if (Entry *E = parseEntry(&*I))
700 EntryArrayContents.push_back(E);
704 } else if (Key == "external-contents") {
707 "entry already has 'contents' or 'external-contents'");
711 if (!parseScalarString(I->getValue(), Value, Buffer))
713 ExternalContentsPath = Value;
714 } else if (Key == "use-external-name") {
716 if (!parseScalarBool(I->getValue(), Val))
718 UseExternalName = Val ? FileEntry::NK_External : FileEntry::NK_Virtual;
720 llvm_unreachable("key missing from Keys");
727 // check for missing keys
729 error(N, "missing key 'contents' or 'external-contents'");
732 if (!checkMissingKeys(N, Keys))
735 // check invalid configuration
736 if (Kind == EK_Directory && UseExternalName != FileEntry::NK_NotSet) {
737 error(N, "'use-external-name' is not supported for directories");
741 // Remove trailing slash(es), being careful not to remove the root path
742 StringRef Trimmed(Name);
743 size_t RootPathLen = sys::path::root_path(Trimmed).size();
744 while (Trimmed.size() > RootPathLen &&
745 sys::path::is_separator(Trimmed.back()))
746 Trimmed = Trimmed.slice(0, Trimmed.size()-1);
747 // Get the last component
748 StringRef LastComponent = sys::path::filename(Trimmed);
750 Entry *Result = nullptr;
753 Result = new FileEntry(LastComponent, std::move(ExternalContentsPath),
757 Result = new DirectoryEntry(LastComponent, std::move(EntryArrayContents),
758 Status("", "", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0,
759 0, file_type::directory_file, sys::fs::all_all));
763 StringRef Parent = sys::path::parent_path(Trimmed);
767 // if 'name' contains multiple components, create implicit directory entries
768 for (sys::path::reverse_iterator I = sys::path::rbegin(Parent),
769 E = sys::path::rend(Parent);
771 Result = new DirectoryEntry(*I, llvm::makeArrayRef(Result),
772 Status("", "", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0,
773 0, file_type::directory_file, sys::fs::all_all));
779 VFSFromYAMLParser(yaml::Stream &S) : Stream(S) {}
782 bool parse(yaml::Node *Root, VFSFromYAML *FS) {
783 yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root);
785 error(Root, "expected mapping node");
789 KeyStatusPair Fields[] = {
790 KeyStatusPair("version", true),
791 KeyStatusPair("case-sensitive", false),
792 KeyStatusPair("use-external-names", false),
793 KeyStatusPair("roots", true),
796 DenseMap<StringRef, KeyStatus> Keys(
797 &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0]));
799 // Parse configuration and 'roots'
800 for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E;
802 SmallString<10> KeyBuffer;
804 if (!parseScalarString(I->getKey(), Key, KeyBuffer))
807 if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys))
810 if (Key == "roots") {
811 yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue());
813 error(I->getValue(), "expected array");
817 for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end();
819 if (Entry *E = parseEntry(&*I))
820 FS->Roots.push_back(E);
824 } else if (Key == "version") {
825 StringRef VersionString;
826 SmallString<4> Storage;
827 if (!parseScalarString(I->getValue(), VersionString, Storage))
830 if (VersionString.getAsInteger<int>(10, Version)) {
831 error(I->getValue(), "expected integer");
835 error(I->getValue(), "invalid version number");
839 error(I->getValue(), "version mismatch, expected 0");
842 } else if (Key == "case-sensitive") {
843 if (!parseScalarBool(I->getValue(), FS->CaseSensitive))
845 } else if (Key == "use-external-names") {
846 if (!parseScalarBool(I->getValue(), FS->UseExternalNames))
849 llvm_unreachable("key missing from Keys");
856 if (!checkMissingKeys(Top, Keys))
861 } // end of anonymous namespace
864 DirectoryEntry::~DirectoryEntry() { llvm::DeleteContainerPointers(Contents); }
866 VFSFromYAML::~VFSFromYAML() { llvm::DeleteContainerPointers(Roots); }
868 VFSFromYAML *VFSFromYAML::create(MemoryBuffer *Buffer,
869 SourceMgr::DiagHandlerTy DiagHandler,
871 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
874 yaml::Stream Stream(Buffer, SM);
876 SM.setDiagHandler(DiagHandler, DiagContext);
877 yaml::document_iterator DI = Stream.begin();
878 yaml::Node *Root = DI->getRoot();
879 if (DI == Stream.end() || !Root) {
880 SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node");
884 VFSFromYAMLParser P(Stream);
886 std::unique_ptr<VFSFromYAML> FS(new VFSFromYAML(ExternalFS));
887 if (!P.parse(Root, FS.get()))
893 ErrorOr<Entry *> VFSFromYAML::lookupPath(const Twine &Path_) {
894 SmallString<256> Path;
895 Path_.toVector(Path);
897 // Handle relative paths
898 if (std::error_code EC = sys::fs::make_absolute(Path))
902 return make_error_code(llvm::errc::invalid_argument);
904 sys::path::const_iterator Start = sys::path::begin(Path);
905 sys::path::const_iterator End = sys::path::end(Path);
906 for (std::vector<Entry *>::iterator I = Roots.begin(), E = Roots.end();
908 ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
909 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
912 return make_error_code(llvm::errc::no_such_file_or_directory);
915 ErrorOr<Entry *> VFSFromYAML::lookupPath(sys::path::const_iterator Start,
916 sys::path::const_iterator End,
918 if (Start->equals("."))
922 if (CaseSensitive ? !Start->equals(From->getName())
923 : !Start->equals_lower(From->getName()))
925 return make_error_code(llvm::errc::no_such_file_or_directory);
934 DirectoryEntry *DE = dyn_cast<DirectoryEntry>(From);
936 return make_error_code(llvm::errc::not_a_directory);
938 for (DirectoryEntry::iterator I = DE->contents_begin(),
939 E = DE->contents_end();
941 ErrorOr<Entry *> Result = lookupPath(Start, End, *I);
942 if (Result || Result.getError() != llvm::errc::no_such_file_or_directory)
945 return make_error_code(llvm::errc::no_such_file_or_directory);
948 ErrorOr<Status> VFSFromYAML::status(const Twine &Path, Entry *E) {
949 assert(E != nullptr);
950 std::string PathStr(Path.str());
951 if (FileEntry *F = dyn_cast<FileEntry>(E)) {
952 ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath());
953 assert(!S || S->getName() == F->getExternalContentsPath());
954 if (S && !F->useExternalName(UseExternalNames))
957 S->IsVFSMapped = true;
959 } else { // directory
960 DirectoryEntry *DE = cast<DirectoryEntry>(E);
961 Status S = DE->getStatus();
967 ErrorOr<Status> VFSFromYAML::status(const Twine &Path) {
968 ErrorOr<Entry *> Result = lookupPath(Path);
970 return Result.getError();
971 return status(Path, *Result);
975 VFSFromYAML::openFileForRead(const Twine &Path,
976 std::unique_ptr<vfs::File> &Result) {
977 ErrorOr<Entry *> E = lookupPath(Path);
981 FileEntry *F = dyn_cast<FileEntry>(*E);
982 if (!F) // FIXME: errc::not_a_file?
983 return make_error_code(llvm::errc::invalid_argument);
985 if (std::error_code EC =
986 ExternalFS->openFileForRead(F->getExternalContentsPath(), Result))
989 if (!F->useExternalName(UseExternalNames))
990 Result->setName(Path.str());
992 return std::error_code();
995 IntrusiveRefCntPtr<FileSystem>
996 vfs::getVFSFromYAML(MemoryBuffer *Buffer, SourceMgr::DiagHandlerTy DiagHandler,
998 IntrusiveRefCntPtr<FileSystem> ExternalFS) {
999 return VFSFromYAML::create(Buffer, DiagHandler, DiagContext, ExternalFS);
1002 UniqueID vfs::getNextVirtualUniqueID() {
1003 static std::atomic<unsigned> UID;
1004 unsigned ID = ++UID;
1005 // The following assumes that uint64_t max will never collide with a real
1006 // dev_t value from the OS.
1007 return UniqueID(std::numeric_limits<uint64_t>::max(), ID);
1011 static bool pathHasTraversal(StringRef Path) {
1012 using namespace llvm::sys;
1013 for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path)))
1014 if (Comp == "." || Comp == "..")
1020 void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) {
1021 assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute");
1022 assert(sys::path::is_absolute(RealPath) && "real path not absolute");
1023 assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported");
1024 Mappings.emplace_back(VirtualPath, RealPath);
1029 llvm::raw_ostream &OS;
1030 SmallVector<StringRef, 16> DirStack;
1031 inline unsigned getDirIndent() { return 4 * DirStack.size(); }
1032 inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); }
1033 bool containedIn(StringRef Parent, StringRef Path);
1034 StringRef containedPart(StringRef Parent, StringRef Path);
1035 void startDirectory(StringRef Path);
1036 void endDirectory();
1037 void writeEntry(StringRef VPath, StringRef RPath);
1040 JSONWriter(llvm::raw_ostream &OS) : OS(OS) {}
1041 void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> IsCaseSensitive);
1045 bool JSONWriter::containedIn(StringRef Parent, StringRef Path) {
1046 using namespace llvm::sys;
1047 // Compare each path component.
1048 auto IParent = path::begin(Parent), EParent = path::end(Parent);
1049 for (auto IChild = path::begin(Path), EChild = path::end(Path);
1050 IParent != EParent && IChild != EChild; ++IParent, ++IChild) {
1051 if (*IParent != *IChild)
1054 // Have we exhausted the parent path?
1055 return IParent == EParent;
1058 StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) {
1059 assert(!Parent.empty());
1060 assert(containedIn(Parent, Path));
1061 return Path.slice(Parent.size() + 1, StringRef::npos);
1064 void JSONWriter::startDirectory(StringRef Path) {
1066 DirStack.empty() ? Path : containedPart(DirStack.back(), Path);
1067 DirStack.push_back(Path);
1068 unsigned Indent = getDirIndent();
1069 OS.indent(Indent) << "{\n";
1070 OS.indent(Indent + 2) << "'type': 'directory',\n";
1071 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n";
1072 OS.indent(Indent + 2) << "'contents': [\n";
1075 void JSONWriter::endDirectory() {
1076 unsigned Indent = getDirIndent();
1077 OS.indent(Indent + 2) << "]\n";
1078 OS.indent(Indent) << "}";
1080 DirStack.pop_back();
1083 void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) {
1084 unsigned Indent = getFileIndent();
1085 OS.indent(Indent) << "{\n";
1086 OS.indent(Indent + 2) << "'type': 'file',\n";
1087 OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n";
1088 OS.indent(Indent + 2) << "'external-contents': \""
1089 << llvm::yaml::escape(RPath) << "\"\n";
1090 OS.indent(Indent) << "}";
1093 void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries,
1094 Optional<bool> IsCaseSensitive) {
1095 using namespace llvm::sys;
1099 if (IsCaseSensitive.hasValue())
1100 OS << " 'case-sensitive': '"
1101 << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n";
1102 OS << " 'roots': [\n";
1104 if (!Entries.empty()) {
1105 const YAMLVFSEntry &Entry = Entries.front();
1106 startDirectory(path::parent_path(Entry.VPath));
1107 writeEntry(path::filename(Entry.VPath), Entry.RPath);
1109 for (const auto &Entry : Entries.slice(1)) {
1110 StringRef Dir = path::parent_path(Entry.VPath);
1111 if (Dir == DirStack.back())
1114 while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) {
1119 startDirectory(Dir);
1121 writeEntry(path::filename(Entry.VPath), Entry.RPath);
1124 while (!DirStack.empty()) {
1135 void YAMLVFSWriter::write(llvm::raw_ostream &OS) {
1136 std::sort(Mappings.begin(), Mappings.end(),
1137 [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) {
1138 return LHS.VPath < RHS.VPath;
1141 JSONWriter(OS).write(Mappings, IsCaseSensitive);
1144 VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(const Twine &_Path,
1146 DirectoryEntry::iterator Begin,
1147 DirectoryEntry::iterator End,
1148 std::error_code &EC)
1149 : Dir(_Path.str()), FS(FS), Current(Begin), End(End) {
1150 if (Current != End) {
1151 SmallString<128> PathStr(Dir);
1152 llvm::sys::path::append(PathStr, (*Current)->getName());
1153 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr.str());
1161 std::error_code VFSFromYamlDirIterImpl::increment() {
1162 assert(Current != End && "cannot iterate past end");
1163 if (++Current != End) {
1164 SmallString<128> PathStr(Dir);
1165 llvm::sys::path::append(PathStr, (*Current)->getName());
1166 llvm::ErrorOr<vfs::Status> S = FS.status(PathStr.str());
1168 return S.getError();
1171 CurrentEntry = Status();
1173 return std::error_code();
1176 vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_,
1178 std::error_code &EC)
1180 directory_iterator I = FS->dir_begin(Path, EC);
1181 if (!EC && I != directory_iterator()) {
1182 State = std::make_shared<IterState>();
1187 vfs::recursive_directory_iterator &
1188 recursive_directory_iterator::increment(std::error_code &EC) {
1189 assert(FS && State && !State->empty() && "incrementing past end");
1190 assert(State->top()->isStatusKnown() && "non-canonical end iterator");
1191 vfs::directory_iterator End;
1192 if (State->top()->isDirectory()) {
1193 vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC);
1202 while (!State->empty() && State->top().increment(EC) == End)
1206 State.reset(); // end iterator